In C#, why won't a `catch (Exception)` placed before `catch (FileNotFoundException)` compile, and how does the runtime pick which catch block runs?
answer
- top to bottom, first match wins
- derived types before base types
- an unreachable clause is an error
- filters change the rule
basics
~20 sThe runtime tests catch clauses top to bottom and runs only the first whose type matches and whose filter, if any, is true. A general clause first would make the specific one unreachable, so the compiler rejects it with CS0160.
solid answer
~40 sWhen an exception reaches a `try` statement, the runtime checks its `catch` clauses in source order and runs the first one whose type is the exception's type or one of its base types, and whose `when` filter, if present, returns true; at most one catch block runs. `FileNotFoundException` derives from `IOException`, which derives from `SystemException` and then `Exception`, so a `catch (Exception)` above `catch (FileNotFoundException)` would always win. The compiler therefore reports CS0160: "A previous catch clause already catches all exceptions of this or of a super type ('Exception')". Order clauses from most derived to least derived. A clause with a filter is exempt, since its filter can still decline, and a typeless `catch { }` must be last (CS1017 otherwise). A `finally` block runs after whichever catch block ran.
code
plaintext · 1 lineorder.cs(9,8): error CS0160: A previous catch clause already catches all exceptions of this or of a super type ('Exception')go deeper
Recall that catch clauses are checked top to bottom, only the first match runs, and specific types go before general ones.
Explain first-match semantics, why CS0160 is an error, why a filtered clause is exempt, and where a general catch must go.
Show you check real base types before relying on a base clause, and that you prefer filters over catch, test and rethrow for partial handling.
Frame catch ordering as part of a team's handling convention: narrow catches near the failure, broad ones only at boundaries that log and decide.
## How a catch clause is chosen A `try` statement can carry several **catch clauses**, each naming an exception type and optionally a `when` **filter**. When an exception propagates out of the `try` block, the runtime picks a handler like this: 1. It looks at the catch clauses **in source order, top to bottom**. 2. A clause **matches by type** when the thrown exception's runtime type is the named type or **derives from it**. `catch (IOException)` therefore matches a `FileNotFoundException`. 3. If the clause has a `when` filter, the filter runs; the clause matches only if it returns `true`. 4. The **first** matching clause wins, and **at most one catch block runs** for a given exception. Later clauses are not consulted, even if one of them would have been a closer fit. 5. If no clause matches, the exception keeps propagating to the caller's `try` statements; when a handler further up accepts it, the `finally` block of this statement (if any) runs as the stack unwinds past it. Notice what step 4 implies: the runtime does **not** search for the most specific clause. Order is the only tie-breaker, which is why order is something the compiler checks. ## The exception hierarchy decides what "specific" means "Specific" means "more derived". The file-handling types show why `catch (Exception)` swallows everything below it: | Exception type | Base types, nearest first | |---|---| | `FileNotFoundException` | `IOException`, `SystemException`, `Exception` | | `DirectoryNotFoundException` | `IOException`, `SystemException`, `Exception` | | `UnauthorizedAccessException` | `SystemException`, `Exception` | | `ArgumentNullException` | `ArgumentException`, `SystemException`, `Exception` | A common surprise in this table: `UnauthorizedAccessException` is **not** an `IOException`, so `catch (IOException)` does not catch "access denied" on a file. ## Why the wrong order is a compile error If a clause can never be reached because an earlier clause catches the same type or one of its base types, the compiler refuses the code. Writing `catch (Exception)` and then `catch (FileNotFoundException)` produces **CS0160**: "A previous catch clause already catches all exceptions of this or of a super type ('Exception')". This is an error, not a warning, because the second block is dead code that the author clearly expected to run. The related rules, all checked by the compiler: - A **general catch clause**, `catch { }` with no type, matches anything and must be **last**; a clause after it is error **CS1017**. - `catch (Exception)` followed by a general `catch { }` compiles with warning **CS1058**: everything is already caught, and non-`Exception` objects thrown by other languages arrive wrapped in `RuntimeWrappedException` anyway. - A clause **with a filter** may name a type that is the same as or less derived than a later clause: `catch (Exception ex) when (ex is UnauthorizedAccessException)` above `catch (IOException)` compiles, because the filter can still return `false` and let the exception reach the later clause. - Several clauses may name the **same type** if they differ by filters; an unfiltered one for that type must come last among them. ## A worked example The second code example has four clauses. For a missing file, `File.ReadAllText` throws `FileNotFoundException`. The first clause matches by type, but its filter (the file name ends with `.tmp`) returns `false`. The second clause, `catch (IOException)`, matches by base type and runs, printing `io: FileNotFoundException`. The third and fourth clauses are never consulted. ## Where finally fits In a `try-catch-finally` statement, the `finally` block runs **after** the chosen catch block finishes, and it still runs if that catch block throws a new exception. If no clause matched and a handler further up the stack accepts the exception, `finally` runs on the way out as the stack unwinds. ## Practical ordering rules - List clauses from **most derived to least derived**; let CS0160 catch slips. - Catch only types you can actually handle at this level; a broad `catch (Exception)` belongs where a component can log and decide, which is a design question of its own. - Look up the real base type before relying on a base-class clause, as the `UnauthorizedAccessException` row shows. - Prefer a `when` filter to a type test and rethrow inside a catch block when only some instances of a type are yours to handle.
- Why can `catch (Exception ex) when (...)` appear above `catch (IOException)` without CS0160?A filtered clause does not catch every exception of its type; the filter can return `false` and send the exception on to later clauses. The compiler therefore treats the later, more specific clause as reachable. Only an unfiltered clause for a base type makes the clauses after it unreachable.
- If two catch clauses both match, does the runtime pick the more specific one?No. The first matching clause in source order runs and the others are never consulted. That is exactly why the compiler forbids a base-type clause above a derived-type clause: with first-match semantics the derived clause could never run.
- the runtime picks the most specific matching catch clause regardless of order
- every matching catch block runs, from top to bottom
- catch (IOException) also handles UnauthorizedAccessException on a file
- putting catch (Exception) first only produces a warning
- a general catch { } can go anywhere in the list