Try catch block is used for exception handling in Java. The code (or set of statements) that can throw an exception is placed inside try block and if the exception is raised, it is handled by the corresponding catch block. In this guide, we will see various examples to understand how to use try-catch for exception handling in java.
Try block in Java
As mentioned in the beginning, try block contains set of statements where an exception can occur. A try block is always followed by a catch block or finally block, if exception occurs, the rest of the statements in the try block are skipped and the flow immediately jumps to the corresponding catch block.
Note: A try block must be followed by catch blocks or finally block or both.
Syntax of try block with catch block
try{ //statements that may cause an exception }catch(Exception e){ //statements that will execute when exception occurs }
Syntax of try block with finally block
try{ //statements that may cause an exception }finally{ //statements that execute whether the exception occurs or not }
Syntax of try-catch-finally in Java
try{ //statements that may cause an exception }catch(Exception e){ //statements that will execute if exception occurs }finally{ //statements that execute whether the exception occurs or not }
Note: It is upto the programmer to choose which statements needs to be placed inside try block. If programmer thinks that certain statements in a program can throw a exception, such statements can be enclosed inside try block and potential exceptions can be handled in catch blocks.
Catch block in Java
A catch block is where you handle the exceptions, this block must immediately placed after a 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
try { //statements that may cause an exception } catch (exception(type) e(object)) { //error handling code }
Example: try catch in Java
If an exception occurs in try block then the control of execution is passed to the corresponding catch block. As discussed earlier, 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, let’s 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 handle 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.
Example of Multiple catch blocks
class Example2{ public static void main(String args[]){ try{ int a[]=new int[7]; a[4]=30/0; System.out.println("First print statement in try block"); } catch(ArithmeticException e){ System.out.println("Warning: ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Warning: ArrayIndexOutOfBoundsException"); } catch(Exception e){ System.out.println("Warning: Some Other exception"); } System.out.println("Out of try-catch block..."); } }
Output:
Warning: ArithmeticException Out of try-catch block...
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
A finally block contains a block of code that always executes regardless of whether an exception occurs or not. See the snippet below. I have covered this in a separate tutorial here: java finally block.
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Handle exception of type ExceptionType2
} finally {
// Code that will always execute
}
rajeev says
How to determine which will be better to handle exception all of the these below:
try catch,throw,throws.
If we can handle all type of exception using try catch then why we need throw or throws
Naveen says
Try-Catch is the best to handle exceptions
throws is only for compiletime exceptions
throw cluase is usefull if you want to throw new exception which are not mentioned in java.lang package
Kalyan Reddy says
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.
Pawan says
what does the rest of code which placed out of catch block.
And what will happen, if finally block will use in nested try?
abhishek says
when in catch block there is one class “exception”which includes all the exception types then why we use multiple catches block..?
Rohith says
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.
Vinay R says
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….
Thanks in advance.
T
Puennendu Paul says
because ArithmeticException is done before ArrayIndexOutOfBoundsException. You will see that, after arithmetic operation is done the result will assigned to the array.
nikunj ramani says
if first exception is genereted then execute corresponding catch block & second exception is ignore…u can try alternate exception…
Nimmy says
very nice and Simple article. good work!!
Birampal singh says
Q1. how many try in one java program?
Q2. how many catch in one java program?
Q3. how many finally in one java program?
thanks
Purnendu Paul says
Ans. of Q2.: More than one catch can be used under a try.
Nawal Sah says
What is the parameter datatype of catch block?
Abhinabo says
What if there is an error/exception in the catch block?
Shaun says
you should know if the catch block needed another try catch nessted. best way to avoid this would be to validate all data first anyway.
eg.
If(userInputVariable == 0) {
System.out.println(“You cannont divide by 0)
return
}
This would be better than using a try catch block.
use them as little as possible
Chandu says
Why we declare throws at method level signature?
atul says
a catch clause may catch exceptions of which type justification
a:error
b:throwable
c:exception
d:string
Purnendu Paul says
catch(Exception e){}
is not working at all. After compilation it shows——
“incompatible types: Exception cannot be converted to Throwable”
What should I do?
Ranjitha says
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…
Rajat says
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.
vijay says
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…
Shilpa says
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.
nikunj ramani says
can we define more than 1 try block in same class?????
Rohith says
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.
rash says
when in catch block there is one class “exception”which includes all the exception types then why we use multiple catches block..?
Abhishek Wadhwa says
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”);
}
widyasaagar says
how many try blocks can be used under single class in a program
shakir says
Here we are using catch block…what is the need and use of using finally block?
lavanya says
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