Csharp/CSharp Tutorial/Language Basics/Try Catch

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

A try, catch, and finally block without Exception class declaration

<source lang="csharp">using System; class MainClass {

 public static void Main()
 {
   try
   {
     int zero = 0;
     Console.WriteLine("In try block: attempting division by zero");
     int myInt = 1 / zero;
     Console.WriteLine("You never see this message!");
   }
   catch
   {
     Console.WriteLine("In catch block: an exception was thrown");
   }
   finally
   {
     Console.WriteLine("In finally block: do any cleaning up here");
   }
 }

}</source>

In try block: attempting division by zero
In catch block: an exception was thrown
In finally block: do any cleaning up here

Catch exception with wrong type inside a function

<source lang="csharp">using System; class MainClass {

   static void AFunction()
   {
       
       try {
           int Zero = 0;
           int j = 22 / Zero;
       } catch (ArgumentOutOfRangeException e) // this exception doesn"t match
       {
           Console.WriteLine("OutOfRangeException: {0}", e);
       }
       Console.WriteLine("In AFunction()");
   }
   public static void Main()
   {
       try
       {
           AFunction();
       }
       // this exception doesn"t match
       catch (ArgumentException e)
       {
           Console.WriteLine("ArgumentException {0}", e);
       }catch(Exception ee){
           Console.WriteLine("Exception {0}", ee);
       }
   }

}</source>

Exception System.DivideByZeroException: Attempted to divide by zero.
   at MainClass.AFunction()
   at MainClass.Main()

Catch statement without exception variable

<source lang="csharp">using System; class MainClass {

  static void Main()
  {
     int x = 10, y = 0;
     
     try { 
     
        x = x/y; 
     
     }catch (System.IndexOutOfRangeException) { 
     
        Console.WriteLine("catch clause"); 
     
     } finally { 
     
        Console.WriteLine("finally clause"); 
     
     }
  }

}</source>

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
   at MainClass.Main()
finally clause

Catch System.NullReferenceException

<source lang="csharp">using System; class MainClass {

  static void Main()
  {
     try { 
     
        string str = null;
        str.ToUpper();
     
     }catch (System.NullReferenceException) { 
     
        Console.WriteLine("catch clause"); 
     
     } finally { 
     
        Console.WriteLine("finally clause"); 
     
     }
  }

}</source>

catch clause
finally clause

Exception Handling Fundamentals

C# exception handling is managed via four keywords: try, catch, throw, and finally.


<source lang="csharp">try {

       // block of code to monitor for errors
   }
   catch (ExcepType1 exOb) {
       // handler for ExcepType1 
   }
   catch (ExcepType2 exOb) {
       // handler for ExcepType2 
   }
   .
   .
   finally{
   
   }</source>

If no exception is thrown by a try block, no catch statements will be executed and program control resumes after the catch statement.

Exception handling with trying and catching

<source lang="csharp">using System; class MainClass{


   public static void Main(){
       Console.WriteLine("Before catch");
       int Zero = 0;
       try {
           int j = 22 / Zero;
       } catch (Exception e) {
           Console.WriteLine("Exception " + e.Message);
       }
       
       Console.WriteLine("After catch");
   }

}</source>

Before catch
Exception Attempted to divide by zero.
After catch

Handle error gracefully and continue.

<source lang="csharp">using System;

class MainClass {

 public static void Main() { 
     try { 
       int j= 0;
       int i = 5/j;
     } 
     catch (DivideByZeroException) { 
       // catch the exception 
       Console.WriteLine("Can"t divide by Zero!"); 
     } 
 } 

}</source>

Can"t divide by Zero!

How to handle a specific exception

<source lang="csharp">using System; class MainClass{

 public static void Main() {
   try {
     int zero = 0;
     Console.WriteLine("In try block: attempting division by zero");
     int myInt = 1 / zero;
   } catch (DivideByZeroException myException) {
     Console.WriteLine("Message = " + myException.Message);
     Console.WriteLine("StackTrace = " + myException.StackTrace);
   }
 }

}</source>

In try block: attempting division by zero
Message = Attempted to divide by zero.
StackTrace =    at MainClass.Main()

Let the C# runtime system handle the error.

<source lang="csharp">using System;

class MainClass {

 public static void Main() { 
   int[] nums = new int[4]; 

   Console.WriteLine("Before exception is generated."); 

   // Generate an index out-of-bounds exception. 
   for(int i=0; i < 10; i++) { 
     nums[i] = i; 
     Console.WriteLine("nums[{0}]: {1}", i, nums[i]); 
   } 

 } 

}</source>

Before exception is generated.
nums[0]: 0
nums[1]: 1
nums[2]: 2
nums[3]: 3
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at MainClass.Main()

Use a nested try block.

<source lang="csharp">using System;

class MainClass {

 public static void Main() { 
   int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; 
   int d = 0;

   try { // outer try 
     for(int i=0; i < 10; i++) { 
       try { // nested try 
         Console.WriteLine(numer[i] + " / " + 
                            numer[i] + " is " + 
                            numer[i]/d); 
       } 
       catch (DivideByZeroException) { 
         // catch the exception 
         Console.WriteLine("Can"t divide by Zero!"); 
       } 
     } 
   }  
   catch (IndexOutOfRangeException) { 
     // catch the exception 
     Console.WriteLine("No matching element found."); 
     Console.WriteLine("Fatal error -- program terminated."); 
   } 
 } 

}</source>

Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
No matching element found.
Fatal error -- program terminated.

Use multiple catch statements.

<source lang="csharp">using System;

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."); 
     } 
   } 
 } 

}</source>

Can"t divide by Zero!
Can"t divide by Zero!
Can"t divide by Zero!
No matching element found.
No matching element found.
No matching element found.
No matching element found.
No matching element found.
No matching element found.
No matching element found.

Use the "catch all" catch statement.

<source lang="csharp">using System;

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."); 
     } 
   } 
 } 

}</source>

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.
Some exception occurred.