Java2all.com  

Try and catch





Share This Topic -

Try and catch with example in java:

We have already seen introduction about try and catch block in java exception handling.

Now here is the some examples of try and catch block.

EX :

 public class TC_Demo 
{
	public static void main(String[] args) 
	{
		int a=10;
		int b=5,c=5;
		int x,y;
		try
		{
			x = a / (b-c);
		}
		catch(ArithmeticException e)
		{
			System.out.println("Divide by zero");
		}
		y = a / (b+c);
		System.out.println("y = " + y);
		
	}

}

 
Output :
Divide by zero
y = 1
 
Note that program did not stop at the point of exceptional condition.It catches the error condition, prints the error message, and continues the execution, as if nothing has happened.
 
If we run same program without try catch block we will not gate the y value in output. It displays the following message and stops without executing further statements.
 
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Thrw_Excp.TC_Demo.main(TC_Demo.java:10)
 
Here we write ArithmaticException in catch block because it caused by math errors such as divide by zero.
 
Now how to display description of an exception ?
 
You can display the description of thrown object by using it in a println() statement by simply passing the exception as an argument. For example;

catch (ArithmeticException e)

{

            system.out.pritnln(“Exception:” +e);

}

Multiple catch blocks :

?It is possible to have multiple catch blocks in our program.

EX :

public class MultiCatch 
{
	public static void main(String[] args) 
	{
		int a [] = {5,10};
		int b=5;
		try
		{
			int x = a[2] / b - a[1];
		}
		catch(ArithmeticException e)
		{
			System.out.println("Divide by zero");
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println("Array index error");
		}
		catch(ArrayStoreException e)
		{
			System.out.println("Wrong data type");
		}
		int y = a[1]/a[0];
		System.out.println("y = " + y);
	}
}

 
Output :
Array index error
y = 2
 
Note that array element a[2] does not exist. Therefore the index 2 is outside the array boundry.
 
When exception in try block is generated, the java treats the multiple catch statements like cases in switch statement.
 
The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.
 
When you are using multiple catch blocks, it is important to remember that exception subclasses must come before any of their superclasses.
 
This is because a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses.
 
Thus, a subclass will never be reached if it comes after its superclass. And it will result into syntax error.

 

// Catching super exception before sub

EX :

class etion3
{
	public static void main(String args[])
	{
		int num1 = 100;
		int num2 = 50;
		int num3 = 50;
		int result1;

		try
		{
			result1 = num1/(num2-num3);
			System.out.println("Result1 = " + result1);
		}
		
		catch (Exception e)
		{
			System.out.println("This is mistake. ");
		}
		catch(ArithmeticException g)
		{
			System.out.println("Division by zero");
			
		}
	}
}

 
Output :
 
If you try to compile this program, you will receive an error message because the exception has already been caught in first catch block.
 
Since ArithmeticException is a subclass of Exception, the first catch block will handle all exception based errors,
 
including ArithmeticException. This means that the second catch statement will never execute.
 
To fix the problem, revere the order of the catch statement. 

Nested try statements :

The try statement can be nested.

That is, a try statement can be inside a block of another try.

Each time a try statement is entered, its corresponding catch block has to entered.

The catch statements are operated from corresponding statement blocks defined by try. 

EX :

 public class NestedTry 
{
		public static void main(String args[])
		{
			int num1 = 100;
			int num2 = 50;
			int num3 = 50;
			int result1;
				
			try
			{
				result1 = num1/(num2-num3);
				System.out.println("Result1 = " + result1);
				try 
				{
					result1 = num1/(num2-num3);
					System.out.println("Result1 = " + result1);
				}
				catch(ArithmeticException e)
				{
					System.out.println("This is inner catch");
				}
			}
			catch(ArithmeticException g)
			{
				System.out.println("This is outer catch");
			}
		}
}

 
Output :
This is outer catch