Multiple catch blocks
Context: A try block can be followed by multiple catch blocks, each handling a different exception type. This allows fine-grained error recovery. The runtime executes the first catch block whose exception type matches the thrown exception. More specific types must appear before more general ones.
Usage Example
Section titled “Usage Example”using System;using System.IO;
class Program{ static void Main() { try { string input = Console.ReadLine(); int number = int.Parse(input); Console.WriteLine(10 / number); } catch (DivideByZeroException ex) { Console.WriteLine("Cannot divide by zero."); } catch (FormatException ex) { Console.WriteLine("Invalid number format."); } catch (IOException ex) { Console.WriteLine("I/O error."); } catch (Exception ex) { Console.WriteLine($"Other error: {ex.Message}"); } }}Output console (example input “0”)
Section titled “Output console (example input “0”)”dotnet run0Cannot divide by zero.Important notes
Section titled “Important notes”- Only one
catchblock executes. - The generic
catch (Exception)must be last. - You can also have a
catchwithout arguments (not recommended).
Real-world usage example
Section titled “Real-world usage example”File processing – Separate FileNotFoundException, UnauthorizedAccessException, IOException, and a final generic catch for logging.
See .NET docs on multiple catch blocks.