Programs on Exception Handling in Java for Interview

In this blog post I will be sharing programs on exception handling in java with output. By going through below coding questions, you will be able to brush up exception handling concepts in short time. To make this blog post easy, I have also shared the explanation at the end of each question.
Without further delay, let's go straight to the questions.

Read Also : Difference between Checked and Unchecked Exception in Java

1. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[]) 
    {
        try 
        {
            System.out.print("A");
            int num = 99/0;
            System.out.print("B");
        }
        catch(ArithmeticException ex) 
        {
            System.out.print("C");
        }
        catch(Exception ex)
        {
            System.out.print("D");
        }
        System.out.print("E");
    }
}



Output : 
ACE

Explanation :
Being the first line of try block A will print.In next line, try block throws the ArithmeticException. Once an exception is thrown from the try block then there is no further execution of it. As a result B is not printed.
ArithmeticException is caught by first catch block, hence C is printed. Program will continue its execution. It skips second catch block as there is currently no exception being thrown. At last, it will print E.


2. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[]) 
    {
        try 
        {
            System.out.print("A");
            int num = 99/0;
            System.out.print("B");
        }
        catch(ArithmeticException ex) 
        {
            System.out.print("C");
        }
        catch(Exception ex)
        {
            System.out.print("D");
        }
        finally
        {
            System.out.print("E");
        }    
    }
}



Output : 
ACE

Explanation :
If you use an optional finally block in your code, it will always be invoked. finally block invocation does not depend on whether an exception in the corresponding try is thrown or not, and regardless of whether a thrown exception is caught or not.


3. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[]) 
    {
        try 
        {
            System.out.print("A");
            int num = 99/0;
            System.out.print("B");
        }
        catch(ArithmeticException ex) 
        {
            System.out.print("C");
        }
        catch(Exception ex)
        {
            System.out.print("D");
        }
        finally
        {
            System.out.print("E");
        } 
        System.out.print("F");
    }
}



Output : 
ACEF

Explanation :
Main takeaway from the above program is code after finally block executes i.e it print F.


4. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[]) 
    {
        try 
        {
            System.out.print("A");
            int num = 99/0;
            System.out.print("B");
        }
        
        System.out.print("C");        
        
        catch(ArithmeticException ex) 
        {
            System.out.print("D");
        }
    }
}


Output : 
Compilation Error
/JavaHungry.java:4: error: 'try' without 'catch', 'finally' or resource declarations

Explanation :
You can not have code between try, catch or finally blocks.

5. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[]) 
    {
        try 
        {
            System.out.print("A");
            int num = 99/0;
            System.out.print("B");
        }
        catch(ArithmeticException ex) 
        {
            System.out.print("C");
            System.exit(0);
        }
        catch(Exception ex)
        {
            System.out.print("D");
        }
        finally
        {
            System.out.print("E");
        } 
        System.out.print("F");
    }
}



Output :
AC

Explanation :
This is one of the most important java interview question. Using System.exit(0) in the try/catch block results in  finally block does not execute. You can see above program does not print E. This is because System.exit(0) command terminates running java virtual machine. Hence no more execution of current program after this line. This is the only scenario where finally block does not execute.

6. What will be the output of the below program?
 
public class JavaHungry {
    public static void main(String args[])
    {
        try
        {
            System.out.print("A");
            int num = 99/0;
            System.out.print("B");
        }
        finally
        {
            System.out.print("C");
        }
        System.out.print("D");
    }
}


Output :
AC
Exception
in thread "main" java.lang.ArithmeticException: / by zero
    at JavaHungry.main(JavaHungry.java:7)

Explanation : 
After printing A, Exception thrown in try block is not caught and hence propagate to finally block. As we know finally block is always executed (except one scenario explained in Q4), hence, it will print C. It will not print D since the exception thrown by try block is not caught/handled.

7. What will be the output of the below program?


class SubException extends Exception { } 
class SubSubException extends SubException { } 
public class JH 
{ 
    public void doStuff() throws SubException {} 
} 
class JH2 extends JH 
{
    public  void doStuff() throws SubSubException {} 
} 
class JH3 extends JH 
{
    public  void doStuff() throws Exception {} 
}
class JH4 extends JH 
{
    public  void doStuff(int x) throws Exception {} 
}
class JH5 extends JH 
{
    public  void doStuff()  {} 
}

Output :
Compilation fails due to line  public void doStuff() throws Exception {}

Explanation :
An overriding method can not throw a broader exception (Exception is broader than SubException) than the method it's overriding.

8. What will be the output of the below program?


public class JavaHungry {
    public static void main(String args[])
    {
        try 
        {      
            System.out.print("A");        
            throw new Exception(); 
        } 
        catch (Exception e) 
        {
            System.out.print("B");
        } 
        finally
        { 
            System.out.print("C");
            int num = 7/0; 
            System.out.print("D");
        }
        System.out.print("E");
    }
}

Output :
ABC
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at JavaHungry.main(JavaHungry.java:16)


Explanation :
Exception in the finally block does not get caught/handled. Hence, terminate the java virtual machine. As a result code does not print D and E.

9. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[])
    {
        try
        {
            System.out.print("A");
            throw new Exception();
        }
        catch (Exception e)
        {
            try
            {
                try 
                {
                    throw new Exception();
                }
                catch (Exception ex) 
                {
                    System.out.print("B");
                }
                throw new Exception();
            }
            catch (Exception exc)
            {
                System.out.print("C");
            }
            finally
            {
                System.out.print("D");
            }
        }
        finally
        {
            System.out.print("E");
        }
        System.out.print("F");
    }
}

Output :
ABCDEF

Explanation:
The whole purpose of above question is to show you that catch block can throw an exception and contain try/catch/finally block as well. You can see that code compiles and execute fine.

10. What will be the output of the below program?


public class JavaHungry {
    public static void main(String args[])
    {
        try 
        {   
            System.out.print("A");
            throw 99; 
        } 
        catch (int ex) 
        {
            System.out.print("B");
        } 
    }
}

Output :
Compilation Errors 

/JavaHungry.java:7: error: incompatible types: int cannot be converted to Throwable
            throw 99;
            ^
/JavaHungry.java:9: error: unexpected type
        catch (int ex)
               ^
  required: class
  found:    int
2 errors



Explanation:
Only throwable objects ( Objects which are subclass of any Throwable class) can be thrown as exception in java. Since we are trying to throw int (primitive data type) as exception , hence we get compilation error.  

11. What will be the output of the below program?

public class JavaHungry {
    public static void main(String args[])
    {
        try 
        {   
            int arr[]= {1, 2, 3, 4, 5}; 
            for (int i = 0; i <= 5; i++) 
            { 
                System.out.print ("Array elements are : " + arr[i] + "\n"); 
            } 
        } 
        catch (Exception e) 
        { 
            System.out.println ("Exception : " + e); 
        } 
        catch (ArrayIndexOutOfBoundsException ex) 
        { 
            System.out.println ("ArrayIndexOutOfBoundsException : "+ ex); 
        }  
    }
}

Output :
Compilation Error

/JavaHungry.java:16: error: exception ArrayIndexOutOfBoundsException has already been caught
        catch (ArrayIndexOutOfBoundsException ex)
        ^
1 error


Explanation :
All catch blocks must be arranged from most specific to more general. If you have a catch clause for both ArrayIndexOutOfBoundsException and Exception , you must put the catch for ArrayIndexOutOfBoundsException first in your code. Otherwise ArrayIndexOutOfBoundsException would be caught by catch(Exception e), because a catch argument can catch the specified exception or its subtypes. As a result compiler will stop you from defining catch clauses that can never be reached.


That's all for the day. Please mention in comments if you find any tricky questions or programs on exception handling in java.

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry