catch exceptions

In this chapter you will learn:

  1. Use multiple catch statements
  2. Use the 'catch all' catch statement

Use multiple catch statements

using System; //from   ja  v  a 2 s  . c  om
 
class MainClass { 
  public static void Main() { 
    int[] numer = { 4, 8, 16}; 
    int j=0;
    
    for(int i=0; i < 10; i++) { 
      try { 
        Console.WriteLine(numer[i] + " / " + 
                           numer[i] + " is " + 
                           numer[i]/j); 
      } 
      catch (DivideByZeroException) { 
        // catch the exception 
        Console.WriteLine("Can't divide by Zero!"); 
      } 
      catch (IndexOutOfRangeException) { 
        // catch the exception 
        Console.WriteLine("No matching element found."); 
      } 
    } 
  } 
}

The code above generates the following result.

Use the 'catch all' catch statement

using System; //ja  v  a 2 s  .  com
 
class MainClass { 
  public static void Main() { 
    int[] numer = { 4, 8}; 
    int d = 0;
    
    for(int i=0; i < 10; i++) { 
      try { 
        Console.WriteLine(numer[i] + " / " + 
                           numer[i] + " is " + 
                           numer[i]/d); 
      } 
      catch { 
        Console.WriteLine("Some exception occurred."); 
      } 
    } 
  } 
}

The code above generates the following result.

Some exception occurred./* ja v a  2s . c om*/
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.
Some exception occurred.

Next chapter...

What you will learn in the next chapter:

  1. What is finally block in exception handling
  2. finally is always executed
  3. Dispose a StreamWriter in finally block
Home » C# Tutorial » Exception
Exception
Exception classes
try...catch
catch exceptions
finally
throw exception
System exception
User-Defined Exception Classes