18 Jan Java Exception Handling
The normal flow of a program disrupts when an exception occurs. This stops the Java program and an error message generates. Consider, Exception as an abnormal condition, which needs to be handled, and Exception Handling as a mechanism used to handle it. This includes handling runtime errors like ClassNotFoundException, IOException, RemoteException, etc.
The following errors can occur while running a Java program:
- Wrong Data as Input
- Opening a File that does not exist at the same location
Code without Exception Handling
Before moving further, let us run a Java code without handling the exceptions.
1 2 3 4 5 6 7 8 9 |
class Studyopedia { public static void main(String[] args) { int[] marks = {90, 95, 88, 80}; System.out.println(marks[5]); } } |
Output
The output displays an error but we are not handling it using try…catch:
1 2 3 4 |
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4 at Studyopedia.main(Main.java:5) |
Now, we will see how to handle the above code with Exception Handling in Java.
Exception Handling in Java
To handle Exceptions, the following concepts are defined in Java:
- try catch in Java
- finally in Java
- throw in Java
Let us learn about them one by one with examples:
try catch in Java
To catch exceptions in Java, use the try…catch pair. The code goes inside both try catch, and is called the protected code. The try block cannot be used alone and is followed by either catch statement or a finally block. Let us see the syntax:
1 2 3 4 5 6 7 8 |
try { // The try block to set the code } catch(Exception e) { // The catch block to handle errors } |
Handle Exceptions with try catch
Let us now see an example to handle exceptions in Java with try…catch:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Studyopedia { public static void main(String[] args) { try { int[] marks = {90, 95, 88, 80}; System.out.println(marks[5]); } catch (Exception e) { System.out.println("Some Issue"); } } } |
Output
1 2 3 |
Some Issue |
Handle Exceptions with try catch and display the exception
We can also display the exception. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
class Studyopedia { public static void main(String[] args) { try { int[] marks = {90, 95, 88, 80}; System.out.println(marks[5]); } catch (Exception e) { System.out.println("The Exception :" + e); } } } |
Output
1 2 3 |
The Exception :java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4 |
The above displays the exact error i.e., the elements are 4, but the value is searched for index 5.
Multiple catch blocks in Java
After a try block, we can add more than one catch block. The exception is thrown to the 1st catch block.
Let us see the syntax of the catch block in Java:
1 2 3 4 5 6 7 8 9 |
try { // The try block to set the code } catch (ExceptionType1 e1) { // The catch block to handle errors } catch (ExceptionType2 e2) { // The catch block to handle errors } |
Only one catch block executes since only a single exception occurs at a time. The multiple catch blocks should be ordered accordingly. The catch for ArithmeticException, ArrayIndexOutOfBoundsException, etc. should come before Exception.
Let us see an example. Here, we have set the ArithmeticException and ArrayIndexOutOfBoundsException, but since the error is related to an array out of bound, therefore the catch which gets executed is ArrayIndexOutOfBoundsException:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
Class Studyopedia { public static void main(String[] args) { try { int[] marks = {90, 95, 88, 80}; System.out.println(marks[5]); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception"); } catch (Exception e) { System.out.println("Exception"); } } } |
Output
1 2 3 |
ArrayIndexOutOfBounds Exception |
finally in Java
The finally in Java executes a code after try catch. Whether the exception is handled or not, the statements in the finally executes. Therefore, add any key code or statement you want to display irrespective of the result inside the finally block. Let us see the syntax of the finally block in Java:
1 2 3 4 5 6 7 8 9 10 11 |
try { // The try block to set the code } catch (ExceptionType1 e1) { // The catch block to handle errors } catch (ExceptionType2 e2) { // The catch block to handle errors } finally { // The finally block executes always. } |
Let us see an example of finally in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Studyopedia { public static void main(String[] args) { try { int[] marks = {90, 95, 88, 80}; System.out.println(marks[5]); } catch (Exception e) { System.out.println("Some Issue"); } finally { System.out.println("The finally executes."); System.out.println("The code ends."); } } } |
Output
1 2 3 4 5 |
Some Issue The finally executes. The code ends. |
throw keyword in Java
To throw an exception, the throw keyword is used. It throws an exception explicitly. The throw keyword is followed by an exception type, like ArithmeticException, ArrayIndexOutOfBoundsException, SecurityException, etc.
Let us see an example wherein we will throw and error if a student gets less than 50 marks and failed the exam:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Studyopedia { static void verifyMarks(int age) { if (age < 50) { throw new ArithmeticException("Failed : You must get above 50 to pass the exam."); } else { System.out.println("Congratulations! You passed the exam."); } } public static void main(String[] args) { // The marks is less than 50 i.e. student failed the exam verifyMarks(45); } } |
Output
1 2 3 4 5 |
Exception in thread "main" java.lang.ArithmeticException: Failed : You must get above 50 to pass the exam. at Studyopedia.verifyMarks(Main.java:4) at Studyopedia.main(Main.java:13) |
If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.
For Videos, Join Our YouTube Channel: Join Now
No Comments