Advertisement



< Prev
Next >



C# try-catch Block





C# provides us a try-catch block, which allows us to handle an exception thrown in an executing program, A try-catch block is made up of two individual blocks - a try block and a catch block.





The catch block declares a type of exception that it is going to catch and handle. If the declared exception-type in catch block is of an exact type or a parent class type of the type of exception thrown by try block, the exception is caught within this catch block and the program continues its normal execution without ending abruptly.











How to catch an exception using try-catch block?


Exception thrown is an object of a certain type exception class. In order to catch an exception of a particular type, we have to make sure that our catch block has declared an exception-type which matches the type of exception that is thrown by the try block.


Let's understand this by an example here.
//C# Example of try-catch block 

using System;

class TryCatch
{
public static void Main(String[] ar)
{
	//Local variables 
	int a=10, b=0, c;
		
	//Defining the try-catch block
	try
	{
		//ArithmeticException i.e. Divide by zero exception is thrown here
		c=a/b; 	
		
		Console.WriteLine(c);
	}	
	catch(DivideByZeroException exp) //matching ArithmeticExcecption is declared in "catch block"
	{
		//Printing the message associated to the caught exception	
		Console.WriteLine("We have an Exception - "+ exp); 
	}		

	Console.WriteLine("Outside try-catch block");
} 		
}


Output :


We have an Exception - System.DivideByZeroException: Attempted to divide by zero.
   at TryCatch.Main(String[] ar)
Outside try-catch block


As you can see, an exception of type DivideByZeroException i.e. "Divide by zero" is thrown when a statement enclosed within the try block is executed. This exception is caught by the catch block because it is declared with a matching exception of type DivideByZeroException.

As the thrown exception DivideByZeroException is caught by the catch block, hence, the program does not end abruptly and it continues to successfully execute the statement next to the try-catch block, which prints a message - "Outside try-catch block".



Note: When an exception is thrown in a statement within a try block, the remaining statements in the try-block are not executed( even after the exception is caught by the catch-block), but the program doesn't end abruptly and it continues to execute the statements next the try-block.


Advertisement




You can catch a thrown exception by its parent class type


Exception thrown is an object of a certain type exception class. In order to catch an exception of a particular type, we have to make sure that our catch block has either declared an exception-type which is an exact type of the exception thrown by the try block or a parent class of the thrown exception type.


Let's understand this by an example here.
//C# Example of try-catch block
//where a catch block has specified an exception type which is a subclass of the thrown exception type.

using System;

class TryCatch
{
public static void Main(String[] ar)
{
	//Local variables 
	int a=10, b=0, c;
		
	//Defining the try-catch block
	try
	{
		//DivideByZeroExceptio is thrown here, which is subclass of ArithmeticException type of exception
		c=a/b; 	
		
		Console.WriteLine(c);
	}	
	catch(ArithmeticException exp) //Matching parent class type i.e. ArithmeticExcecption is declared in "catch block"
	{
		//Printing the message associated to the caught exception	
		Console.WriteLine("We have an Exception - "+ exp); 
	}		

	Console.WriteLine("Outside try-catch block");
} 		
}


Output :


We have an Exception - System.DivideByZeroException: Attempted to divide by zero.
   at TryCatch.Main(String[] ar)
Outside try-catch block


As you can see, an exception of type DivideByZeroException i.e. "Divide by zero" is thrown when a statement enclosed within the try block is executed. This exception is caught by the catch block because it has declared the parent exception class of the thrown DivideByZeroException type i.e. ArithmeticExcecption

As the thrown exception DivideByZeroException is caught by the catch block, hence, the program does not end abruptly and it continues to successfully execute the statement next to the try-catch block, which prints a message - "Outside try-catch block".






Mismatch in exception declared and exception thrown





Let us understand this by an example here.
//C# Example of mismatch of an exception thrown and an exception declared in the catch block


using System;

class TryCatch2
{

//Defining the Opr() method of the class 
public void Opr()
{
	try
	{
		int a = 100, b = 0;
			
		//ArithmeticException is thrown here
		Console.WriteLine(a/b); 
		
		Console.WriteLine("The Opr() method ends");
	}
	catch(NullReferenceException nullExp) //Non-matching exception-type is declared in this catch block
	{
		Console.WriteLine("We have an Exception - "+nullExp);
	}
	Console.WriteLine("Outside try-catch block");
} 

//Defining the Main() method
public static void Main(String[] arr)
{
	//Creating an object of the class
	TryCatch2 ob = new TryCatch2();

	try
	{
		//Enclosing the call to Opr() method in try block
		ob.Opr(); 	
	}
	catch(DivideByZeroException e)
	{
		Console.WriteLine("Exception thrown by the Opr() method is caught in the Main() method:");
		Console.WriteLine(e);
	}

} 
}


Output:


Exception thrown by Opr() method is caught in Main() method:
System.DivideByZeroException: Attempted to divide by zero.
   at TryCatch2.Opr()
   at TryCatch2.Main(String[] arr)

//C#  Not specifying the identifier of the an exception type in the catch block.

using System;
using System.IO;

class A
{
public static void Main(String[] arr)
{
	try
	{
		//Initiating to read a file
		FileStream f = new FileStream("E:\\file.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); 

		int i = 0;  
        	while ((i = f.ReadByte()) != -1)  
        	{  
       		     Console.Write((char)i);  
        	}  
	        f.Close();  
	}
	catch(IOException)	//Not declaring the identifier of the exception type.
	{
		Console.WriteLine("An IOException is thrown");
	}
}
}

Although by using the identifier of the exception type, we could gather the information about the thrown exception, but if we are very certain about the thrown exception and already know its reason then we could omit the identifier and that's fine as well.

In the next, article, we will talk about the finally block.



Please share this article -





< Prev
Next >
< C# Exception Propagation
C# Multiple Catch Blocks >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement