CSharp examples for Custom Type:try catch finally
A catch clause specifies what type of exception to catch.
This must either be System.Exception or a subclass of System.Exception.
Catching System.Exception catches all possible errors.
class Test { static void Main (string[] args) { try { byte b = byte.Parse (args[0]); Console.WriteLine (b); } catch (IndexOutOfRangeException ex) { Console.WriteLine ("Please provide at least one argument"); } catch (FormatException ex) { Console.WriteLine ("That's not a number!"); } catch (OverflowException ex) { Console.WriteLine ("You've given me more than a byte!"); } } }
Only one catch clause executes for a given exception.
If you want to include a safety net to catch more general exceptions, you must put the more specific handlers first .
An exception can be caught without specifying a variable if you don't need to access its properties:
catch (OverflowException) // no variable { ... }
Furthermore, you can omit both the variable and the type (meaning that all exceptions will be caught):
catch { ... }