try block
In our program the code which may cause an exception is called risky code. We have to place risky code inside try-block and the corresponding handling code inside catch block.
Java try block must be followed by either catch or finally block or try could be followed by both catch and finally blocks.
catch block
Java catch block is used to handle the exception by declaring the type of exception within the parameter. The declared exception must be the parent class exception ( i.e., Exception) or the generated exception type. However, the good approach is to declare the generated type of exception.
We cannot write any other code between try and catch block. So try-block should immediately followed by catch block.
We can write multiple catch blocks for a single try block.
Example 01 : Syntax of Java try-catch
1 2 3 4 5 |
try { // Risky code } catch (Exception_Class_Name refName) { // Handling code } |
Below are the examples and use cases with try-catch block
Example 02 : Code without exception handling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.vidvaan.corejava.exception05.trycatchblock; // Code without exception handling code public class Example02NoTryCatch { public static void main(String[] args) { System.out.println("main begin"); int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); System.out.println("main end"); } } |
Output :
main begin
Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.vidvaan.corejava.exception05.trycatchblock.Example02NoTryCatch.main(Example02NoTryCatch.java:7)
In the above example, Line number 7 and 8 are related, But Line number 10 is no way related to 7 and 8. As there is invalid arithmetic operation on line 7, So Line 8 is not executed. That is acceptable. But here important thing is line 10 is not executed even it is no way related to line number 7 and 8. It happens because we didn’t handle the exception.
Example 03 : Code with exception handling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.vidvaan.corejava.exception05.trycatchblock; //Code with exception handling code public class Example03WithTryCatch { public static void main(String[] args) { try { System.out.println("main begin"); int data = 5 / 0; //It Will throw exception System.out.println("Result of division : " + data); System.out.println("main end"); } catch (ArithmeticException e) { // Here we are catching exception } } } |
In the above example we put all the code in try block. So our code is ready to handle the exception and program will not abnormally terminated when exception raised. But the bad thing is when exception raised non-exception related code also not executed. So we need to put only related code in the try block. Let’s fix this in the next example.
Example 04 : Related task code in try block
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package com.vidvaan.corejava.exception05.trycatchblock; //Related task code in try block public class Example04RelatedCodeInTryBlock { public static void main(String[] args) { System.out.println("main begin"); try { // Only related code in try block int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); } catch (ArithmeticException e) { } System.out.println("main end"); } } |
Output :
main begin
main end
In the above program, exception raised in the try block then it is handled by catch block. Even exception raised, ‘main end’ printed because we handled the exception. But here we don’t know what exception raised and where it is raised. To know that we need to print the exception stack trace info as shown in the following example.
Example 05 : Print Exception details from the Exception object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.vidvaan.corejava.exception05.trycatchblock; // print the exception details in catch block public class Example05PrintExceptionDetails { public static void main(String[] args) { System.out.println("main begin"); try { int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); } catch (ArithmeticException e) { // print exception details e.printStackTrace(); } System.out.println("main end"); } } |
Output :
main begin
java.lang.ArithmeticException: / by zero
at com.vidvaan.corejava.exception05.trycatchblock.Example05PrintExceptionDetails.main(Example05PrintExceptionDetails.java:9)
main end
This is perfect !!! We got exception on line 10, So line 11 is not executed, then control goes to catch block and then line 15 executed and prints the exception details. Line 17 executed successfully. So we are making sure that even exception raised the remaining code executes without abnormal termination.
But in catch block we are not handling the exception, we are just printing exception. Handling could be done as per business needs, there are so many ways we could handle this exception
Example 06 : Handling Exception in catch block by printing issue details
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.vidvaan.corejava.exception05.trycatchblock; //Handling Exception in catch block by printing issue details public class Example06HandleByPrintingIssueDetails { public static void main(String[] args) { System.out.println("begin"); try { int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); } catch (ArithmeticException e) { // Here we are printing issue related details System.out.println("We can't divide with zero"); } System.out.println("main end"); } } |
Output :
begin
We can’t divide with zero
main end
In the above program, We are printing reason for the issue, User may fix the issue by looking into this message.
Example 07 : Handling Exception in catch block with default value
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.vidvaan.corejava.exception05.trycatchblock; //Handling Exception in catch block with default value public class Example07HandleWithDefaultValue { public static void main(String[] args) { System.out.println("main begin"); try { int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); } catch (Exception e) { System.out.println("We can't divide with zero, so dividing with default value'1'"); int data = 50 / 1; System.out.println("Result of division : " + data); } System.out.println("main end"); } } |
Output :
main begin
We can’t divide with zero, so dividing with default value’1′
Result of division : 50
main end
In this example, if we get exception we could just divide with one(as a default divider). Like this we can handle the exception in many ways as per business needs.
Example 08: catch super class of raised exception class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.vidvaan.corejava.exception05.trycatchblock; //catch super class of raised exception class public class Example08CatchSuperClassOfRaisedException { public static void main(String[] args) { System.out.println("main begin"); try { int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); } catch (Exception e) { // Actual exception raised is 'ArithmeticException' // But we are catching 'Exception' which is super class of 'ArithmeticException' System.out.println("We can't divide with zero"); } System.out.println("main end"); } } |
Output :
main begin
We can’t divide with zero
main end
Here we are catching the exception with super class ‘Exception’. But it is advisable to catch specific exception instead of generalized exception.
Example 09 : catch a different exception class instead raised exception
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.vidvaan.corejava.exception05.trycatchblock; //catch a different exception class instead raised exception public class Example09CatchDifferentExceptionInsteadRaisedException { public static void main(String[] args) { System.out.println("main begin"); try { int data = 50 / 0; // It will throw exception System.out.println("Result of division task : " + data); } catch (NullPointerException e) { // JVM will throw 'ArithmeticException' // But we are catching 'NullPointerException' System.out.println("We can't divide with zero"); } System.out.println("main end"); } } |
Output :
main begin
Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.vidvaan.corejava.exception05.trycatchblock.Example09CatchDifferentExceptionInsteadRaisedException.main(Example09CatchDifferentExceptionInsteadRaisedException.java:11)
Here we are catching the NullPointerException, But JVM raised ArithmeticException. But our catch block could not catch the ArithmeticException. So always we need to catch issue related exception.
Example9 : Multiple tasks in one try block
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.vidvaan.corejava.exception05.trycatchblock; //Multiple tasks in one try block public class Example10MultipleTasksInOneTryBlock { public static void main(String[] args) { System.out.println("main begin"); try { // Task One int data = 5 / 0; // It will throw exception System.out.println("Result of division : " + data); // Task Two int arr[] = { 1, 3, 5, 7 }; System.out.println("2nd element of array: " + arr[1]); } catch (Exception e) { e.printStackTrace(); } System.out.println("main end"); } } |
Output :
main begin
java.lang.ArithmeticException: / by zero
at com.vidvaan.corejava.exception05.trycatchblock.Example10MultipleTasksInOneTryBlock.main(Example10MultipleTasksInOneTryBlock.java:12)
main end
Here we have two tasks code in one try block. We should not do that, because if first tasks fails to execute then second task also will not get executed, even it is no way related to the first task. So always put different tasks in different try blocks as shown below.
Example 11: Multiple tasks in multiple try blocks
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.vidvaan.corejava.exception05.trycatchblock; //Multiple tasks in multiple try blocks public class Example11MultipleTasksInMultipleTryBlocks { public static void main(String[] args) { System.out.println("main begin"); // Task one try { int data = 50 / 0; // It will throw exception System.out.println("Result of division : " + data); } catch (ArithmeticException e) { e.printStackTrace(); } // Task two try { int arr[] = { 1, 3, 5, 7 }; System.out.println("2nd element of array: " + arr[1]); // It will throw exception } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); } System.out.println("main end"); } } |
Output :
main begin
java.lang.ArithmeticException: / by zero
at com.vidvaan.corejava.exception05.trycatchblock.Example11MultipleTasksInMultipleTryBlocks.main(Example11MultipleTasksInMultipleTryBlocks.java:12)
2nd element of array: 3
main end
Here we are handling different tasks in different try blocks and handling them with their specific exceptions.