C# Exception Handling

1. Normal Case

    1.1 try-catch

     static   void  Main( string [] args)
    
{
       
try
        
{
            
//Code which can cause problems(exceptions)
        }

        
catch( Exception_type e)
        
{
            
//Code for handling the problems(exceptions)
        }

    }

   A. If exception occurs inside the try block, the control transfers to the catch block, then to the line of code immediately following the catch() block.

//  A.
     static   void  Main( string [] args)
    
{
        
int x = 0;
        
int div = 0;
        
try
        
{
            div 
= 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
catch (DivideByZeroException ex)
        
{
            Console.WriteLine(
"Catch Block: Exception occured!");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }


/* Out put: 
Catch Block: Exception occured!
Ending Block: It's the end!
*/

 

   B. Otherwise, it will go to the line of code following the catch() block directly.    

//  B.
     static   void  Main( string [] args)
    
{
        
int x = 2;
        
int div = 0;
        
try
        
{
            div 
= 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
catch (DivideByZeroException ex)
        
{
            Console.WriteLine(
"Catch Block: Exception occured!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }


/*   Output:
Try Block: Not executed line!
Ending Block: It's the end!
   */

 

      1.2 try-finally

     static   void  Main( string [] args)
    
{
        
try
        
{
            
//Code which can cause problems(exceptions)
        }

        
finally
        
{
            
//Code for handling the problems(exceptions)
            
//Code for cleanup.
            
//Code will always execute regardless of whether an an exception has occured or not
        }

    }

   

   A. If exception occurs inside the try block, because there is no exception handling catch block, the execution will get terminated. But before the termination of the program, statements inside the finally block will get executed. That's why we only can see "Finally BLock...", but no "Ending block..."

//  A.
     static   void  Main( string [] args)
    
{
        
int x = 0;
        
int div = 0;
        
try
        
{
            div 
= 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }



/* Output
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.
   at Program.Main(String[] args) in ....................*.cs:line **
Finally Block: We always come here!

*/

 

    B. Although there is no exception occurs, the code inside the Finally() blocks will still be execute. We can find this from the output.

//  B.    
     static   void  Main( string [] args)
    
{
        
int x = 2;
        
int div = 0;
        
try
        
{
            div 
= 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }


/* Output:
Try Block: Not executed line!
Finally Block: We always come here!
Ending Block: It's the end!

*/

 

    1.3 try-catch-finally

     static   void  Main( string [] args)
    
{
        
try
        
{
            
//Code which can cause problems(exceptions)
        }

        
catch (Exception_type e)
        
{
            
//Code for handling the problems(exceptions)
        }

        
finally
        
{
            
//Code for cleanup.
            
//Code will always execute regardless of whether an an exception has occured or not
        }

    }

 

    A. If exception occurs inside the try block, the control transfers to the catch block, then to the finally block.

//  A.
     public   static   void  Main()
    
{
        
int x = 0;
        
int div = 0;
        
try
        
{
            div 
= 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
catch (DivideByZeroException ex)
        
{
            Console.WriteLine(
"Catch Block: Exception occured!");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }


/* Output
Catch Block: Exception occured!
Finally Block: We always come here!
Ending Block: It's the end!

*/

 

   B. If there is exception occurs inside the try block, the control will ignore the catch block, go to finally() block directly. Anyway, the code inside finally() block will be execute.

//  B.
     public   static   void  Main()
    
{
        
int x = 2;
        
int div = 0;
        
try
        
{
            div 
= 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
catch (DivideByZeroException ex)
        
{
            Console.WriteLine(
"Catch Block: Exception occured!");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }


/*
Try Block: Not executed line!
Finally Block: We always come here!
Ending Block: It's the end!
*/

 

2. Multiple Catch()

     try-catch1-catch2-catch3

     static   void  Main( string [] args)
    
{
        
try
        
{
            
//Code which can cause problems(exceptions)
        }

        
catch (Exception_type e1)
        
{
            
//Code for handling the first exception
        }

        
catch (Exception_type e2)
        
{
            
//Code for handling the second exception
        }

        
catch (Exception_type e3)
        
{
            
//Code for handling the third exception
        }

        
finally
        
{
            
//Code for cleanup.
            
//Code will always execute regardless of whether an an exception has occured or not
        }

    }

 The catch() blocks are examined in order from top to bottom. The runtime compares the type of exception that has occured with the exception type declared in each catch() block to find a match - either an exact match or a supertype match, then executes the code inside the first such match.

The catch() block including derived exception types should always precede the catch() block wich including the base exception types. Otherwise, the catch() with derived types will never get executed.

     static   void  Main( string [] args)
    
{
        
try
        
{
            
//Code which can cause problems(exceptions)
        }

        
catch (Exception e1)
        
{
            Console.WriteLine(
"Catch Block: Exception occured!");
            
// This block will catch all types of Exceptions, INCLUDING IOException specifically.
        }

        
catch (IOException e2)
        
{
            Console.WriteLine(
"Catch Block: IOException occured!");
            
// This block will never be executed because IOException is a derived class of Exception.
        }

        
finally
        
{
            
//.....
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }

 

3. Catch all Exceptions

We can catch all exceptions occured inside the try() block by using a catch() block without arguments, like this: The output will be the same as 1.3A:

     static   void  Main( string [] args)
    
{
        
int x = 0;
        
int div = 0;
        
try
        
{
            
//Code which can cause problems(exceptions)
            div = 100 / x;
            Console.WriteLine(
"Try Block: Not executed line!");
        }

        
catch
        
{
            
//Code for handling the problems(exceptions)
            Console.WriteLine("Catch Block: Exception occured!");
        }

        
finally
        
{
            
//Code for cleanup. 
            
//Code will always execute regardless of whether an an exception has occured or not
            Console.WriteLine("Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!", div);
    }

 

/* Output
Catch Block: Exception occured!
Finally Block: We always come here!
Ending Block: It's the end!

*/

4. Throw Exception

    4.1   throw exception

    A. Inside the try() block, we throw out a general Exception, which will be catched by the second catch() block.

     public   static   void  Main()
    
{
        
try
        
{
            
throw new Exception();
        }

        
catch (DivideByZeroException ex)
        
{
            Console.WriteLine(
"Catch Block: DivideByZeroException occured! No.1");
        }

        
catch (Exception e2)
        
{
            Console.WriteLine(
"Catch Block: General Exception occured! No.2");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!");
    }


/* Output
Catch Block: General Exception occured! No.2
Finally Block: We always come here!
Ending Block: It's the end!
*/

    B. Inside the try() block, we throw out a special Exception - DivideByZeroException(), which will be catched by the first catch() block.

     public   static   void  Main()
    
{
        
try
        
{
            
throw new DivideByZeroException();
         }

        
catch (DivideByZeroException ex)
        
{
            Console.WriteLine(
"Catch Block: DivideByZeroException occured! No.1");
        }

        
catch (Exception e2)
        
{
            Console.WriteLine(
"Catch Block: General Exception occured! No.2");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!");
    }


/* Output
Catch Block: DivideByZeroException occured! No.1
Finally Block: We always come here!
Ending Block: It's the end!
*/

 

    4.2   throw user-defined exception

     In addition to the exception classes provided by the FCL, it's also possible in C# to declare yo own, application-specific exception exception types by extending the System.Exception or any of its derived classes.

using  System;

public   class  vvException : Exception
{
    
int divNum; 

    
public vvException(int divs)
    
{
        
this.divNum = divs;
    }


    
public int Div
    
{
        
get
        
{
            
return divNum;
        }

    }


    
public override string Message
    
{
        
get
        
{
            
return "Error: The dividend can't be "+ Div;
        }

    }

}


public   class  vvCalculation
{
    
public vvCalculation(int div)
    
{
        
if (div == 10)
        
{
            
throw new vvException(div);
        }

    }

}


class  Program
{
    
public static void Main()
    
{
        Console.WriteLine(
"Please input an integer as dividend..");
        
int dividend = Int32.Parse(Console.ReadLine());
        vvCalculation doCalculation;

        
try
        
{
            doCalculation 
= new vvCalculation(dividend);
        }

        
catch (vvException)
        
{
            Console.WriteLine(
"Catch Block: vvException occured! Sorry we don't take 10 as the dividend!");
        }

        
catch (Exception)
        
{
            Console.WriteLine(
"Catch Block: General Exception occured! No.2");
        }

        
finally
        
{
            Console.WriteLine(
"Finally Block: We always come here!");
        }

        Console.WriteLine(
"Ending Block: It's the end!");
    }

}


/* Output
Please input an integer as dividend..
10
Catch Block: vvException occured! Sorry we don't take 10 as the dividend!
Finally Block: We always come here!
Ending Block: It's the end!
*/

 

    4.3   re-throw exception

    For the exceptions we catched in the catch() block, we can re-throw them to the higher context. We can consider to wrap that exception with some additional information before re-throwing it.

class  vvClass
{
    
public void Calculation()
    
{
        
try
        
{
            
int x = 0;
            
int div = 100 / x;
        }

        
catch (DivideByZeroException e)
        
{
            Console.WriteLine(
"Catch Block: Catched exception in lower level!");
            
throw;
        }

    }

}


class  Program
{
    
public static void Main()
    
{
        vvClass vc 
= new vvClass();
        
try
        
{
            vc.Calculation();
        }

        
catch(Exception e)
        
{
            Console.WriteLine(
"Catch Block: Catched exception in higher level!");
        }

        Console.WriteLine(
"Ending Block: It's the end!");
    }

}


/* Output
Catch Block: Catched exception in lower level!
Catch Block: Catched exception in higher level!
Ending Block: It's the end!
*/
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值