As the name suggests, the try catch Java is made up of a try block and a catch block. Try block executes a specific set of instructions and checks for any error to occur. This concept is for the detection of kinds of error which might occur at the time of execution, so all that errors are taken care of before the execution of code. It helps in smooth error-free execution of code.
As stated above, the try block will check a set of instructions for an error to occur and if there is an error then that error is thrown and the catch block will act according to the error thrown by the try block. So for each type of error, we need to define the catch block, which will act accordingly as per the error raised.
So for a good developer/coder this is a very essential concept as the end users may use the application in the wrong way which led to an error and crashing of the app. So for each possible error, there should be a pair of java try catch which take care of the error and don’t let the code to terminate or the app to crash.
Table of Contents
Syntax of java try catch
Let us first see the syntax for a try block. It is very simple :
try
{
// set of instructions which may contain some error
}
So this will execute the code inside the block and see if any error is raised.
But just the try block wouldn’t be of any use because if any error is raised, then we don’t have any catch block to take care of the error. So the try block is always followed by a catch block or a finally block or there can be both of them. First, we see the combination of try catch java and then we will take a look on the finally block.
Syntax of the catch block:
catch(Exception e)
{
// set of instruction to handle this particular exception
}
So if an exception occurs in the try block and if there is a catch block for that particular exception then the statements under that catch block are executed instead of displaying an error. It will help the user also as for any error we can display a message that a user can understand.
There can be multiple catch blocks for a single try block because the statement in the try block can raise different kinds of errors. So for handling each kind of error, we need to create a different catch block and according to the error raised that catch block statements will be executed.
Let us use it in an example for better understanding
Example 1:
// program to divide 100 with the number given by the user
import java.util.Scanner;
public class Ex1
{
public static void main(String []args)
{
// creating a scanner object for taking input
Scanner s = new Scanner(System.in);
System.out.println("Enter number :");
int a = 100;
// taking input from user
int b = s.nextInt();
// dividing 100 by the the input number stored in variable b
float ans = a/b;
// printing the answer
System.out.println("ans = " + ans);
}
}
Output:
Enter number :
10
ans = 10.0
In the above code, we are dividing 100 by the number given by the user, so it would work with a non zero value but if the user enters 0 as the input then the answer will be infinite, and it will give an ArithmeticException. So to deal with this error we can set java to try catch block to handle this ArithmeticException.
import java.util.Scanner;
public class Ex1
{
public static void main(String []args)
{
try
{
Scanner s = new Scanner(System.in);
int a = 100;
int b = s.nextInt();
float ans = a/b;
System.out.println("ans = " + ans);
}
catch(ArithmeticException e)
{
System.out.println("Please enter a non zero value");
}
}
}
So with the help of try catch java if the user enters 0 and the Arithmetic error is raised then the catch block will be executed and the message will be printed “Please enter a non zero value”.
But since we have only created catch for ArithmeticException so in case any other error is raised then that error won’t be taken care of, so we should always create a catch block for every possible error. Also, we can use only Exception keyword instead of specifying the type of exception and that will take care of any exception raised but a good developer or coder should know the different types of error which might occur and accordingly design the catch block with an appropriate message, which would be more user friendly.
Example 2:
public class Ex2
{
public static void main(String args[])
{
try
{
int a[]=new int[7];
a[9]=30; // or a[5]=30/0;
// here a[9]=30 will give ArrayIndexOutOfBoundsException as the //array a is of size 7
// a[5]=30/0 will give ArithmeticException as 30/0 will give infinite
// the below statement will only execute if any exception is not raised // in the above statement
System.out.println("Executed the entire try block without any error");
}
catch(ArithmeticException e)
{
System.out.println("ArithmeticException found please check code");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException found please check code");
}
catch(Exception e)
{
System.out.println("There is some Exception in the code");
}
System.out.println("try catch java code executed");
}
}
Output:
ArrayIndexOutOfBoundsException found please check code
try catch java code executed
This is how the multiple catch code executes.
Java try catch finally
We also have finally block which can be written after java try catch. The finally block will execute regardless of the result of try and catch. So it is like an end statement where we can leave a message that we need to display once the try and catch blocks are executed. It is not necessary that finally block will only execute if there is an error raised and the catch block is used. Even if no error is raised and no catch block is executed then also the finally block will execute.
Try catch finally java example:
public class Ex3
{
public static void main(String[] args)
{
try
{
int[] my_array = {1, 2, 3};
System.out.println(my_array[8]);
}
catch (Exception e)
{
System.out.println("Something is not right, check the code.");
}
finally
{
System.out.println("This is a try catch finally java example");
}
}
}
Output:
Something is not right, check the code.
This is a try catch finally java example
So in the above example since the print statement has an index which does not exist, so it will raise ArrayIndexOutOfBoundsException. It will be taken care by the catch block and after that, the finally block will execute displaying the message that the example is over.