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"); } }
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 } }
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.
1 Response
[…] the previous post, we have seen try-catch block. In this post, we will discuss about the nested try […]