What is try block
A try block is used to surround a set of statements where exceptions may occur.
A try block used with catch and finally block
Also Read
Exception Handling in Java: Hierarchy Example and Types
What is a catch block
A catch block is created followed by a try block.
Whenever an exception is thrown from try block it catches in the appropriate catch block
There can be more than one catch block for a try block.
Syntax of try-catch block
1 2 3 4 5 | try{ //statements to check for exception }catch(ExceptionType e){ //statments to handle exception } |
Java finally block
Java finally block is also associated with a try block.
Finally block is used to release resources that are used in a try block.
like closing a file. closing database connection
Finally block gets always executed when there is an exception or not in try block.
We can use try and finally or try catch and finally.
Syntax of try-catch and finally
1 try and finally
1 2 3 4 5 | try{ //statements to check for exception }finally{ //statments to release resource } |
2 try catch and finally
1 2 3 4 5 6 7 | try{ //statements to check for exception }catch(ExceptionType e){ //statments to handle exception }finally{ //statments to release resource } |
try catch java examples
ArithmeticException Example in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class ExceptionHandling1 { public static void main(String args[]) { int d, a; try { // monitor a block of code for exception. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero." + e); } System.out.println("After catch block."); } } |
Output
1 2 | Division by zero.java.lang.ArithmeticException: / by zero After catch block. |
The exception occurs at the line “a = 42 / d; “, then this exception is thrown, and program control transfers from the
In the line “catch (ArithmeticException e) “ e is a reference of the exception “ArithmeticException”.
When we print the value of “e “ it will print ( java.lang.ArithmeticException:/by zero at Test.main(Test.java:6) )
- ArithmeticException is an exception class that resides in java.lang package.
- “/by zero” is a type of arithmetic exception (divided by zero).
- “Test” is the name of the class.
- “main” is a method in which an exception occurs.
- 6 is the line number in which an exception occurred.
Java try catch multiple exceptions
1 Try and multiple catch blocks
In java programming, when within a try block multiple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class MultiCatchDemo { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = {1}; c[42] = 99; } catch (ArithmeticException e) { System.out.println("You can not divide a number by zero: " + e); } catch (ArrayIndexOutOfBoundsException exc) { System.out.println("Array index out of bounds exception: " + exc); } System.out.println("After try catch blocks."); } } |
When we pass no command-line argument (during run time) then the length of the command-line argument (args. length) is zero means the value of the variable “a” is 0.
Read More: Addition of two numbers using command-line arguments
Then the output is:
1 2 3 4 | Output: c:\> Java MultiCatch a = 0 Divided By zero:java: java.lang.ArithmeticException:/by zero After try/catch |
When we pass one or more command-line arguments ( in this program one command-line argument is passed “test” during run time) then the length of the command-line argument (args. length) is one means value of variable “a” is 1.
Then the output is:
1 2 3 4 | C:\> Java MultiCatch test a = 1 Array index out of bounds exception: java.lang.ArrayIndexOutOfBoundException:42 After try catch |
2 Java try catch multiple exceptions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class MultiCatchDemo { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = {1}; c[42] = 99; } catch (ArithmeticException| ArrayIndexOutOfBoundsException e) { System.out.println("Exception: " + e); } System.out.println("After try catch blocks."); } } |
Unreachable Code in Exception Handling
In Java programming, in a sequence of catch statements exception subclass must come before its superclass.
In a series, if the exception superclass comes before its subclass then the exception subclass would never be reached.
It is known as unreachable code. In Java programming, unreachable code is
Example unreachable code in Exception Handling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class SuperSubCatch { public static void main(String args[]) { try { int a = 0; int b = 55 / a;// divided by zero ArithmeticException } catch (Exception e) { System.out.println("Exception "); } /* This catch is never executed because General class Exception is before then specific class ArithmeticException. */ catch (ArithmeticException e) {// ERROR - unreachable { System.out.println("This is never reached."); } } } |
If we will try to compile this program we will receive an error message stating that the second catch statement is unreachable because ArithmeticException is a subclass of the
Then the first catch statement will handle all
To solve the problem, reverse the order of the catch statement.
Nested try-catch Java statements
In java programming, it is possible to create a try block within another try block. Such a try block is known as a nested try.
Nested try catch Example
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 | class TryNest { public static void main(String args[]) { try { int a = args.length; /* If args.length is zero then the following statement will generate a divide-by-zero ArithmeticException. */ int b = 55 / a; System.out.println("a = " + a); try { // nested try block /* If one command line arg is used, then an Array index out-of-bounds exception will be generated by the following code. */ if (a == 1) { int c[] = {1}; c[42] = 99; // generate an out-of-bounds exception } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch (ArithmeticException e) { System.out.println("You can not divide a number by zero " + e); } } } |
If there is no command-line argument present then the output.
1 2 3 4 | c:> Java NestTry a = 0 Divided By zero:java: java.lang.ArithmeticException:/by zero After try/catch |
If there is no command-line argument present then the output.
1 2 3 4 | c:> Java NestTry one a = 1 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundException:42 After try/catch |
Read More
User-Defined Exception in Java with Examples
Q : When a statement within a try block causes an exception, the remaining statements in the try block
Ans: Will Not be executed
Q: In a try/catch construct, after the catch statement is executed:
Ans: Statement just after the catch is executed
Q: Can you have multiple catch blocks on a try statement
Ans: Yes, as per the need we can have multiple catch blocks on a try statement
Q: To catch an exception, the code that might throw the exception must be enclosed in a ____________
Ans: try block
Q: If an exception occurs in a try-catch block, the code in the finally clause ________.
Ans: Get Executed. If with try block finally is associated then it always gets executed no matter it throws an exception or not.
Q: A try block may be followed by a finally block, without a catch block (Java try without catch).
Ans: Yes we can use try and finally without a catch block.
Q: Exceptions can be thrown by ________.
Ans: Throw statement is used to throw an Exception
Q: When is the code within a catch block executed?
Ans: If an exception occurs within the code in the try block then matched exception in the catch block gets executed.
Java unreported exception How to Handle it
The unreported exception is due to you have checked exception in your program and you are not handling it.
You can handle it
- By using try catch block
- By using throws keyword in method
Which of the following Throwables needs to be declared?
- Error
- RuntimeException
- CheckedException
- Exception
Answer is 3