# Code Smell 184 - Exception Arrow Code

> TL;DR: Don't cascade your exceptions

# Problems

- Readability

- Complexity

# Solutions

1. Rewrite the nested clauses

# Context

In the same way [arrow code](https://maximilianocontieri.com/code-smell-102-arrow-code) is hard to read, handling exceptions is a usual case when we must address the topics in a cascade way.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/18a248332d86061c9cccdf5195a70ca8)
```java
class QuotesSaver {
    public void Save(string filename) {
        if (FileSystem.IsPathValid(filename)) {
            if (FileSystem.ParentDirectoryExists(filename)) {
                if (!FileSystem.Exists(filename)) {
                    this.SaveOnValidFilename(filename);
                } else {
                    throw new I0Exception("File exists: " + filename);
                }
            } else {
                throw new I0Exception("Parent directory missing at " + filename);
            }
        } else {
            throw new ArgumentException("Invalid path " + filename);
        }
    }
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/7d40861212d1d475a25d740f10c8f34e)
```java
public class QuoteseSaver {
    public void Save(string filename) {
        if (!FileSystem.IsPathValid(filename)) {
            throw new ArgumentException("Invalid path " + filename);
        } else if (!FileSystem.ParentDirectoryExists(filename)) {
            throw new I0Exception("Parent directory missing at " + filename);
        } else if (FileSystem.Exists(filename)) {
             throw new I0Exception("File exists: " + filename);
        }
        this.SaveOnValidFilename(filename);
    }
}
```

# Detection

[X] Semi-Automatic 

Some linters warn us when we have this kind of complexity

# Tags

- Exceptions

# Conclusion

Exceptions are less critical than normal cases.

If we need to read more exceptional code than normal then it is time to improve our code.

# Relations

%[https://maximilianocontieri.com/code-smell-102-arrow-code]

%[https://maximilianocontieri.com/code-smell-26-exceptions-polluting]

# Disclaimer

Code Smells are just my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Remy Gieling](https://unsplash.com/@gieling?) on [Unsplash](https://unsplash.com/s/photos/archer)
  
* * *

> An error doesn't become a mistake until you refuse to correct it.

_Orlando Aloysius Battista_

%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
  
