Exception Handling try catch finally blocks in Java

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

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 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

2 try catch and finally

try catch java examples

ArithmeticException Example in Java


Exception occurs at the line “a = 42 / d; “ , then this exception is thrown, program control transfer from  try block to catch block.

Once  catch block has executed program control continue with the next line in a program following entire try/catch statement.

In the line “catch (ArithmeticException e) “  e is a reference of 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 which 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 line number in which exception occured.

Java try catch multiple exceptions

1 Try and multiple catch blocks

In java programming, when within a try block multiple exceptions occur then for handling those multiple exceptions we use multiple catches with a single try block.

When we pass no command line argument (during run time) than the length of command line argument (args.length) is zero means value of variable “a” is 0.

Than the output is:

When we pass one or more command line argument ( in this program one command line argument is passed “test” during run time) than the length of command line argument (args.length) is one means value of variable “a” is  1.

Than the output is:

2 Java try catch multiple exceptions

Unreachable Code in Exception Handling

In Java programming, in a sequence of catch statement exception subclass must come before its super class.

In a series, if exception super class comes before  its subclass than exception sub class would never be reached.

It is known as unreachable code. In Java programming, unreachable code is an compile-time error.    

Example unreachable code in Exception Handling

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 Exception class. 

     Then the first catch statement will handle all exception-based errors, including Arithmetic Exception therefore second catch statement will never execute.

 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 try block is known as nested try.

Nested try catch Example

If there is no command line argument present then the output.

If there is no command line argument present then the output.

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

  1. By using try catch block
  2. By using throws keyword in method

unreported exception

Which of the following Throwables needs to be declared?

  1. Error
  2. RuntimeException
  3. CheckedException 
  4. Exception

Answer is 3

More MCQ

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Throw and Throws Keywords in Java
  4. How To Fix Internal Exception: java.io.ioexception In Minecraft

Throw and Throws Keywords in Java

In java programming, If the exception occurs within the try block it is thrown.

a throw keyword is used to throw an exception

A system-generated exception is automatically thrown by the java run time system but if we want to manually throw an exception, we can do so by using the throw keyword. 

Exception Handling try catch finally blocks in Java

Syntax of throw

           throw    ThrowableInstance;

here, ThrowableInstance must be an object of type Throwable or subclass of Throwable.

Example of throw keyword

In this program new is used to create an instance of NullPointerException and we get two chance to deal with the same error.

In the line  “throw new NullPointerException(“demo”);” 

throw keyword is used to throw  NullPointerException(“demo”). Here we set “demo” is a name of exception.

This NullPointerException(“demo”) catch by catch() method which resides in a demo() method.

 Line “throw e;”  re-throw the exception which is catch by catch() method which resides in a main() method.

Throws Keyword in Java

In a java programming, throws keyword list the type of exception that a method might throw.

throws keyword inform that method throws mentioned exceptions

In the throws clause, we declare all the exceptions that a method can throw.

  Syntax of throws:         


Here, exception1, exception2 are comma, list of the exception that a method can throw.

Example of throws

Explaination: We throws NullPointerException in the line “throw new NullPointerException(“demo”);” .

Here we set “demo” is a name of thread.

This line “throw new NullPointerException(“demo”);” throw the exception which is handled by catch block associated with try within main().

Difference between throw and throws in Java (throw vs throws)

throw keyword is used to throw an exception from method or from a block

throw is used inside method

throw new NullPointerException("demo");

throws keyword is used to inform that a method throws exception(s)

thorws keyword i s used in method header

public Scanner​(File source) throws FileNotFoundException

What is the purpose of the throw statement?

Throw is used to throw an exception from a method or from block of code

what is the difference between throwing an exception and catching an exception?

Throwing an exception can use to throw an exception using the throw keyword.

this can be implicit or explicit

45/0 <- throw ArithmeticException 

throw ArithmeticException(“Denominator can not be zero”);

To catch an exception one or more catch blocks can be used so that program executes properly.

The ______ keyword is used to manually throw an exception in java

The Throw keyword is used to manually throw an exception.

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling in Java with Examples
  3. Exception Handling try catch finally blocks in Java


How to Throw Exceptions


Exception Handling in Java with Examples

Exception Handling in java

To learn about exception handling first you must know what is an exception

What is an Exception in Java

An exception is run time error that can occur due to wrong user input or due to logical error in programming.

Arithmetic Exception Example

Consider a simple example.

Take two integer number from command prompt and divide the number.

The code is

We complice above program

c:\> javac   division.java

while running this program we will pass

two values to program as below

  > java division 10 2

Above two values 10 and 2 known as command  line argument these values are accessed in string [] s.

There s is string array  first value 10 is stored in s[0] and second value is stored in s[1]

S is string array so we converted these string values to integer by calling Integer.parseInt(value)

Here Integer is a class and parseInt is static method used to convert string value to int value.

The converted value is stroed in a and in b

The result of division operation is

                                C= a/b;   //c = 10/2 =5 

It will store value 5 in c.

  Next statement print division is 5

This is our desired result.

What happen if user enters value 10 and 0.

What happen if user enters value 10 and 0.

  Then the statement

                                C= a/b; // c= 10/0 –

   This statement throw arithmetic exception.

    The output is a below.

Exception in thread “main” java.lang.ArithmeticException: / by zero
at division.main(division.java:5)

The above exception is due to Wrong user input.

To handle above situation we can use user input validation or exception handling.

Lets see user input validation here before division operation check whether the value of b is zero or not.

If it is zero information to user and stop the program else perform the division as below.

NumberFormatException Handling

>javac 10 0

divisor should not be zero

This program validate the denominator is zero then print message to user else perform division operation.

Here validation is used to avoid the exception. This is good practice to validate user input to avoid exceptions.

Here we want to learn exception handling so lets see the above program with java exception handling

lets run again above code

>java Division 10 2

Division is 3

>java Division 10 0

Arithmetic Exception

In above program to handle exception try and catch blocked is used.

Inside try block the code is written which can throw exception.

The statements which can throw expection is written inside try block.

To catch the exception a catch block is used with exception type . inside the catch block appropriate exception handling is done.

Catch block executes when exception is thrown from code inside try block.

In above program int c= a/b;

exception is thrown when the value of b is zero so it should be inside try block.

The statement System.out.println(“division is “ + c); is not throwing an exception it is also inside the try block.

If division statement throw an exception. The control is passed to catch block and necessary action is performed inside catch block.

The catch block is only executed if statements inside try block throws an exception.

Lets again execute above program with value 10 and String value lets a 

>javac Division 10 a

Exception in thread "main" java.lang.NumberFormatException: For input string: "a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at division.main(division.java:4)

Here second value is string so throwing above exception

Integer.parseInt (s[1]) throw an exception  because it is unable to convert string to int.

In our program we handled only arithmetic exception

To handle this exception lets modify our code

again compiling and running this code

>javac Division 10 a

Please enter valid number

System.exit(1) is used to exit from program.

Here denominator is not a number so no need to continue the program.

here we used two try block and its corrosponding catch blocks.

If you want we can use one try block and multiple catch block.

Lets again change this code to handle multiple catch in single try block.

Multiple catch blocks java

Here all type of exceptions are checked in try block when an exception is thrown based on exception a catch block is executed.

Exception is parent class for all exceptions.

Any exception thrown can handle by catching exception.

Standing multiple exceptions in program, then general exception should be last catch statement otherwise specific exception catch statement will not reached.

 Which of the following is not an advantage of Java exception handling?

 A. Java separates exception handling from normal processing tasks.
 B. Exception handling improves performance.
 C. Exception handling makes it possible for the caller’s caller to handle the exception.
 D. Exception handling simplifies programming because the error-reporting and error-handling code can be placed at the catch block.

Answer is B

More MCQ

Read More

  1. Exception Handling in Java: Hierarchy Example and Types
  2. Exception Handling try catch finally blocks in Java
  3. Throw and Throws Keywords in Java
  4. How To Fix Internal Exception: java.io.ioexception In Minecraft

Finally Keyword in Java

In java exception handling, any code that we want to must be execute put inside the finally block.

After the execution of try and catch block, finally block executes. try block must be used with either catch or finally, or with both.

Normally when exception occurs then further programs never executes. 

But either exception occurs or not, in both condition finally block executes.

Example1:  write a program to demonstrate the use of finally block with only try.

In the above program, we use two conditions, in the first condition we set array a is “a[100] = 20;”

 than exception occurs the following two lines will never execute

System.out.println(“Never Execute”);

System.out.println(“After try/finally “);

But finally block executes. And output is:

In the second condition, we set array a is “a[5] = 10;”  than there is no exception occurs.

use finally block executes. The output is:

Note: In this program, we have not used catch block, means when an exception will be generated then the program will never execute but finally must be executed .

Example2: write a program to demonstrate the use of finally block with try catch.

In the above program, we uses two condition, in the first condition we set array a is “a[100] = 20;”  than exception occurs the following  line will not execute

            System.out.println(“Never Execute”);

and exception is thrown which is caught bycatch(ArrayIndexOutOfBoundException  e)” after the catch rest of the program will execute. and the output is:

Exception Handling in Java: Hierarchy Example and Types

One of the important topic Exception handling in java

Here we will discuss basics of exceptions, Why Exception handling and its types.

What is Exception in Java

A unwanted event that disrupts the program execution.

In Java all Exceptions are class.

Why Exception Occurs

  1. Due to wrong user input
  2. Incorrect programming logic

Example of Exceptions

  1. Dividing a number by zero 5/0 . It will throw ArithmeticException
  2. Converting a String to number Integer.parseInt("123s"). Exception It will throw NumberFormatException 
  3. Accessing beyond index in Array a[100] when only 5 elements are in array. Throw ArrayIndexOutOfBoundsException

ArithmeticException on Java Program

What is Exception Handling in Java

Exception can terminate the program execution.

To handle unwanted event and to execute rest of the program exception handling is required

On exception Java shows programmer friendly message. To show end used we need to provide custom message

How to Handle Exception in Java

Java provides keywords to handle the exception

Java exception can be handle by 5 keyword  try, catch, throw, throws and finally.

  1. try : Any Program statement that we want to check for exception must be placed  within a try block.
  2. catch  :  If the exception occurs within try block it is thrown. Your code can catch this exception (using catch) and handle it.
  3. throw  :  if an exception arises then this system-generated exception is automatically thrown by Java run time system. To manually throw an exception, throw keyword used.
  4. throws  :  A throws clause lists the type of exception that a method might throw.
  5. finally  :  In programming, we want any code must be executed after the try block completes is placed within a finally block.


try block can be used either with a catch or finally block or with both but try cannot be used alone.

A try can have multiple catch block.

When there is an exception in the try block an appropriate catch block is executed based on the exception.

Exception Hierarchy in java

In java programming, Exception class is a subclass of class Throwable.

Apart from the Exception class, class Error is also derived from class Throwable.

Fig: Exception Hierarchy

Error: In java programming, error is Unrecoverable. It occurs during compile time.

For example, if we write wrong syntax then error will generate during compile time.

Root class of exception in java

Throwable is the root class of exception in Java

Types of Exception in Java

  1. Checked Exception
  2. Unchecked Exception

Checked Exception in java

Exceptions that are checked by compiler is called checked exceptions.

On compiling above program.

Checked Exception in Java
Fig: Checked Exception

To make code executable we must surround Scanner with try and catch the FileNotFoundException.

Here is the list of some checked exception

  1. IllegalAccessException: in java programming, this exception occurs when access to a class is denied.
  2. ClassNotFoundException: this exception occurs when class not found.
  3. NoSuchMethodException : when a requested method dose not exist this exception occurs.
  4. CloneNotSupportedException: in java programming,If you are trying to use the clone method in a classwhere Cloneable interface is not implemented, it throwsCloneNotSupportedException. Clone() method is used to create exactcopy of a object
  5. InterruptedException : in java, when we work with multiple threads then one thread  interrupts another thread.  

Unchecked Exception in Java

Exception condition is not checked by compiler.

Runtime class and its sub classes are known as unchecked exception.

Compiler does not flag any error if there is unchecked exception.

Fig: Unchecked Exception compilation
  1. ArithmeticException : in java programming, this exception, represent the arithmetic error, such as divided-by-zero.
  2. IndexOutOfBoundsException: when some type of index is out of bounds this exception occurs.
    • ArrayIndexOutOfBoundsException: in java programming, this exception represents the Array index is out of bound. This condition arises when we try to access the illegal array index.
    • StringIndexOutOfBoundsException: in java programming, when we access the index outside the bounds of string then this exception occurs.
  3. NegativeArraySizeException: when an array is created with a negative size then this exception arises.
  4. NullPointerException: in java programming, this exception occurs when invalid use of null reference.
  5. IllegalThreadStateException: this exception occurs when the required operation not compatible with the current thread state.

What is difference between checked and unchecked exception in java

Checked Exceptions are checked by compile at compile time.

Unchecked Exceptions are not checked by compiler.

Advantages of Exception Handling in Java

  1. Error handling is separate from Regular code
  2. Propagating Errors Up the Call Stack
  3. Grouping and Differentiating Error Types

Read More

  1. Exception Handling in Java with Examples
  2. Exception Handling try catch finally blocks in Java
  3. Throw and Throws Keywords in Java


Advantages of Exceptions