Bifalgorithm post · Computer science one · Throwing Exceptions

Why should the most specific exception types be caught before general ones?

Why should the most specific exception types be caught before general ones? (Computer science one · Throwing Exceptions) — "Note that the last catch block was…

Ideas in this flowchart

  • Catch blocks must be ordered from most specific to most general.
  • The last catch block catches the generic Exception type.
  • It catches any other type of exception not caught earlier.
  • Catch blocks behave like an if-else-if statement: only the first matching block executes.
  • Catch blocks are mutually exclusive.
  • A catch-all block for generic exceptions should always be placed last.
  • Specific exception types must be caught before general exception types.
Feed/

Why should the most specific exception types be caught before general ones?

No cover

Channel

Computer science one

1 page

"Note that the last catch block was written to catch a generic Exception. This last block will essentially catch any other type of exception. Much like an if-else-if statement, the first type of exception that is caught is the block that will be executed and they are all mutually exclusive. Thus, a “catch all” block like this should always be the last catch block. The most specific types of exceptions should be caught first and the most general types should be caught last."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.