Try Catch in Java – Exception handling

In the previous tutorial we discussed what is exception handling and why we do it. In this tutorial we will see try-catch block which is used for exception handling.

Try block

The try block contains set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both.

Syntax of try block

try{
//statements that may cause an exception
}

While writing a program, if you think that certain statements in a program can throw a exception, enclosed them in try block and handle that exception

Catch block

A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

Syntax of try catch in java

Example: try catch block

If an exception occurs in try block then the control of execution is passed to the corresponding catch block. A single try block can have multiple catch blocks associated with it, you should place the catch blocks in such a way that the generic exception handler catch block is at the last(see in the example below).
The generic exception handler can handle all the exceptions but you should place is at the end, if you place it at the before all the catch blocks then it will display the generic message. You always want to give the user a meaningful message for each type of exception rather then a generic message.

class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
/* We suspect that this block of statement can throw
* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
System.out.println(num2);
System.out.println("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
System.out.println("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
System.out.println("Exception occurred");
}
System.out.println("I'm out of try-catch block in Java.");
}
}

Output:

You should not divide a number by zero
I'm out of try-catch block in Java.

Multiple catch blocks in Java

The example we seen above is having multiple catch blocks, lets see few rules about multiple catch blocks with the help of examples. To read this in detail, see catching multiple exceptions in java.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any other type of exception, this handles all of them. To see the examples of NullPointerException and ArrayIndexOutOfBoundsException, refer this article: Exception Handling example programs.

catch(Exception e){
//This catch block catches all the exceptions
}

If you are wondering why we need other catch handlers when we have a generic that can handle all. This is because in generic exception handler you can display a message but you are not sure for which type of exception it may trigger so it will display the same message for all the exceptions and user may not be able to understand which exception occurred. Thats the reason you should place is at the end of all the specific exception catch blocks

3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception, which is an advanced topic and I have covered it in separate tutorials: user defined exception, throws keyword, throw vs throws.

In the above example there are multiple catch blocks and these catch blocks executes sequentially when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it can handle all exceptions. This catch block should be placed at the last to avoid such situations.

Finally block

I have covered this in a separate tutorial here: java finally block. For now you just need to know that this block executes whether an exception occurs or not. You should place those statements in finally blocks, that must execute whether exception occurs or not.

1. try..catch is to handle the exception at that place itself. Hence, program continues once the associated catch block code is executed. If not caught with associated, it looks for outer try..catch blocks. here, the code following try block will not be executed unless (only finally block is executed). This process continues until this is handled by some catch block and the last option is Java Run time handle, where it prints exception stack.
2. Throws is where you expect some exceptions ( checked or unchecked), but not interested in handling them. So, when exception occurs, it looks for handler in outer try block or in calling method.
3. Throw – is used when User wants to through manually than the system. Suppose, Divide by zero can be caught by system or with try ..catch. In case, yourself want to verify the values of the divider for zero and then can throw your own or already defined exceptions with Throw.
Correct me, if I anything is missing.

It’s because if you want to catch a specific exception and may even write some statements in the block specific to that exception. You can do that with Exception class too. But, you won’t be able to identify the problem easily.
“Exception” is the parent class and will be used to catch mostly generic or unexpected exceptions.

If we write 2 exception in the same try block ex arithmetic exception and array index out of exception and the corresponding catch blocks then the output we ll get only arithmetic exception. why it is not handling array index out of bounds exception. please tell me….

Suppose if a try block has divide by zero exception …and we have two catch blocks like one is exception which covers all exception and another one is specific arithmetic exception…for this statement under which catch block will get print…either exception or arithmetic exception…
Thanks in advance…

If you place Exception catch block first, then the other block(Arithmetic Exception one) will become unreachable and it will show this error “Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception”.

If you place arithmetic exception catch block first, then it will get executed smoothly without any issue.

I have one dought… In catch block already catch(exception e)..is there then why we go for
catch( arthemeticexception e)…..why we write the extra airthrmatic block….exception block is sufficient for that…

if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it has theability to handle all exceptions. This catch block should be placed at the last to avoid such situations.
It’s because if you want to catch a specific exception and may even write some statements in the block specific to that exception. You can do that with Exception class too. But, you won’t be able to identify the problem easily.
“Exception” is the parent class and will be used to catch mostly generic or unexpected exceptions.

Yes. You can declare as many try blocks as you want. Just that each of them should have a catch or finally or both.
They are all independent to each other and there can be multiple catch blocks for each of those “try” blocks.

We use multiple catch block to take actions according to specific exception, Example: You might want to ignore ArithmeticException so you will write
catch(ArithmeticException e){
//Do nothing
}
Now you want to take some action when there is ArrayIndexOutOfBoundsException so you will write
catch(ArrayIndexOutOfBoundsException e){
Log(“Index out of Bound Exception occur, look at the code”);
}

In the example multiple catch blocks in java, the size of array is 7 right…………………………. int a[]=new int[7];
a[4]=30/0;
a[4] means it is referring to index 4…..but why it is showing ArrayIndexOutOfBoundsException