CSharp - Exception catch Clause

Introduction

A catch clause sets the exception type to catch.

This type must either be System.Exception or a subclass of System.Exception.

Catching System.Exception catches all possible errors.

You can handle multiple exception types with multiple catch clauses.

Demo

using System;
class Test/*from ww  w .  j av  a  2s .co  m*/
{
     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!");

         }
     }
}

Result

To include catch for more general exceptions such as System.Exception you must put the more specific handlers first.

An exception can be caught without specifying a variable.

In this way you have no way to access its properties:

catch (OverflowException)   // no variable
{
       ...
}

You can omit both the variable and the type meaning that all exceptions will be caught:

catch { ... }

Related Topics

Quiz