try and catch block in java

In the previous block, we have seen What is Exception Handling? In this post, we will discuss about the try and catch block.

What is a try block?

A try block contains a set of programming statements where exception may occur. It is followed by a catch block which is used to capture the exception occurred in the try block. A try block must followed by catch block or finally block or both, otherwise it will throw a compile time error.

Syntax of try block:

try{
   //set of statements where exceptions may occur
}

What is a catch block?

A catch block must be associated a try block. If any particular exceptions occurs in try block, that exception will be handled by the catch block. The code for exception handling should be written in the catch block.

Syntax of catch Block:

try
{
     //set of statements where exceptions may occur
}
catch (type of exception e)‏
{
     //error handling code
}

Understand the problem without try-catch block:

Let’s take an example where we divide a number with 0.

public class WithoutTryCatchEx {
	public static void main(String[] args){	
		
	      int data=50/0;// It will throw  error (/ by zero)
	      System.out.println("Important steps to be executed");
	}	
}
Output: Exception in thread “main” java.lang.ArithmeticException: / by zero at com.test.SacnnerEx.main(SacnnerEx.java:11)

Observe the output above, we got an error “/ by zero”. But after that step code is not executed. Suppose, we don’t want to stop the execution of the program after error occurred, but requirement it should capture the error and execute rest of the code.

In that case, try-catch block will be helpful. Let’s how.

public class WithoutTryCatchEx {
	public static void main(String[] args){	
		try{
	      int data=50/0;// It will throw  error (/ by zero)
		}catch(ArithmeticException e){
			System.out.println("Error : "+e.getMessage());
			System.out.println("Caught the error");
		}
	      System.out.println("Important steps to be executed");  // program will be executed
	}	
}
Output:
Error : / by zero
Caught the error
Important steps to be executed

In the above program , we have handled the exception in the catch block which is capturing the error. But rest of the code is also executed this time.

Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’.Select the desired category and post your question.
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

1 Response

  1. August 8, 2015

    […] the previous post, we have seen try-catch block. In this post, we will discuss about the nested try […]