Software Design/Catch the most specific type of exception

From Wikiversity
Jump to navigation Jump to search

Examples[edit | edit source]

try {
  // some logic
} catch (e: IOException) {
  // do something - retry the operation, notify the user, etc.
}

Rather than catch (e: Exception) { ... } or Throwable.

Why[edit | edit source]

Code robustness: less likely that bugs in the code wrapped with exception handling would be processed as if they were expected exceptional conditions (such as a network I/O error).

Why not[edit | edit source]

Duplication of logic between handlers of different specific types of exceptions which leads to change amplification, higher probability of inserting bugs in the exception handling logic itself (rather than the logic being wrapped with exception handling), etc. Eliminating this duplication (e. g. via extracting a function) has its own drawbacks.