Java面试题每日10问(11)

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

Java: Exception Handling Interview Questions

1.What is Exception Handling?

  • Exception Handling is a mechanism that is used to handle runtime errors.
  • It is used primarily to handle checked exceptions. Exception handling maintains the normal flow of the program.
  • There are mainly two types of exceptions: checked and unchecked. Here, the error is considered as the unchecked exception.

2.Explain the hierarchy of Java Exception classes?

The java.lang.Throwable class is the root class of Java Exception hierarchy which is inherited by two subclasses: Exception and Error.

在这里插入图片描述

3.What is the difference between Checked Exception and Unchecked Exception?

1) Checked Exception

  • The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions
  • e.g., IOException, SQLException, etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

  • The classes that extend RuntimeException are known as unchecked exceptions
  • e.g., ArithmeticException, NullPointerException, etc. Unchecked exceptions are not checked at compile-time.

4.Is it necessary that each try block must be followed by a catch block?

  • It is not necessary that each try block must be followed by a catch block.
  • It should be followed by either a catch block OR a finally block. So whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
public class Main{  
     public static void main(String []args){  
        try{  
            int a = 1;   
            System.out.println(a/0);  
        }  
        finally  
        {  
            System.out.println("rest of the code...");  
        }  
     }  
}  
      
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...

5. What is finally block?

  • Java finally block is a block used to execute important code such as closing the connection, etc.

  • Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.

  • The finally block follows the try-catch block.
    在这里插入图片描述

6. Can finally block be used without a catch?

Yes, According to the definition of finally block, it must be followed by a try or catch block, therefore, we can use try block instead of catch

7. Is there any case when finally will not be executed?

Finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).

8.What is the difference between throw and throws?

|

throw keywordthrows keyword
1) The throw keyword is used to throw an exception explicitly.The throws keyword is used to declare an exception.
2) The checked exceptions cannot be propagated with throw only.The checked exception can be propagated with throws
3) The throw keyword is followed by an instance.The throws keyword is followed by class.
4) The throw keyword is used within the method.The throws keyword is used with the method signature.
5) You cannot throw multiple exceptions.You can declare multiple exceptions, e.g., public void method()throws IOException, SQLException.

🔔Note:

Java throw keyword

throw new exception_class("error message");

  • throw keyword is used to throw an exception explicitly.

  • We specify the exception object which is to be thrown.

  • The Exception has some message with it that provides the error description.

  • These exceptions may be related to user inputs, server, etc.

  • throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception.

  • Exception is the sub class of Throwable and the user-defined exceptions usually extend the Exception class

1)1: Throwing Unchecked Exception

If we throw unchecked exception from a method, it is must to handle the exception or declare in throws clause.

public class TestThrow1 {   
    //function to check if person is eligible to vote or not   
    public static void validate(int age) {  
        if(age<18) {  
            //throw Arithmetic exception if not eligible to vote  
            throw new ArithmeticException("Person is not eligible to vote");    
        }  
        else {  
            System.out.println("Person is eligible to vote!!");  
        }  
    }  
    //main method  
    public static void main(String args[]){  
        //calling the function  
        validate(13);  
        System.out.println("rest of the code...");    
  }    
}    

在这里插入图片描述

2)Throwing Checked Exception

Every subclass of Error and RuntimeException is an unchecked exception in Java. A checked exception is everything else under the Throwable class.

import java.io.*;  
  
public class TestThrow2 {   
  
    //function to check if person is eligible to vote or not   
    public static void method() throws FileNotFoundException {  
  
        FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");  
        BufferedReader fileInput = new BufferedReader(file);  
  
      
        throw new FileNotFoundException();  
      
    }  
    //main method  
    public static void main(String args[]){  
        try  
        {  
            method();  
        }   
        catch (FileNotFoundException e)   
        {  
            e.printStackTrace();  
        }  
        System.out.println("rest of the code...");    
  }    
}  

在这里插入图片描述
3) Throwing User-defined Exception

exception is everything else under the Throwable class.

// class represents user-defined exception  
class UserDefinedException extends Exception  
{  
    public UserDefinedException(String str)  
    {  
        // Calling constructor of parent Exception  
        super(str);  
    }  
}  
// Class that uses above MyException  
public class TestThrow3  
{  
    public static void main(String args[])  
    {  
        try  
        {  
            // throw an object of user defined exception  
            throw new UserDefinedException("This is user-defined exception");  
        }  
        catch (UserDefinedException ude)  
        {  
            System.out.println("Caught the exception");  
            // Print the message from MyException object  
            System.out.println(ude.getMessage());  
        }  
    }  
}   

在这里插入图片描述

9.Can subclass overriding method declare an exception if parent class method doesn’t throw an exception?

Yes but only unchecked exception not checked.

🔔Note:

Some of the rules are listed below:

  • If the superclass method does not declare an exception
    • If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
  • If the superclass method declares an exception
    • If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

1)If the superclass method does not declare an exception

Rule 1: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception.

import java.io.*;    
class Parent{   
  
  // defining the method   
  void msg() {  
    System.out.println("parent method");  
    }    
}    
    
public class TestExceptionChild extends Parent{    
  
  // overriding the method in child class  
  // gives compile time error  
  void msg() throws IOException {    
    System.out.println("TestExceptionChild");    
  }  
  
  public static void main(String args[]) {    
   Parent p = new TestExceptionChild();    
   p.msg();    
  }    
}    

在这里插入图片描述

Rule 2: If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception.

import java.io.*;    
class Parent{    
  void msg() {  
    System.out.println("parent method");  
  }    
}    
    
class TestExceptionChild1 extends Parent{    
  void msg()throws ArithmeticException {    
    System.out.println("child method");    
  }    
  
  public static void main(String args[]) {    
   Parent p = new TestExceptionChild1();    
   p.msg();    
  }    
}   

在这里插入图片描述
2)If the superclass method declares an exception

Rule 1: If the superclass method declares an exception, subclass overridden method can declare the same subclass exception or no exception but cannot declare parent exception.

subclass overridden method declares parent exception

`import java.io.*;    
class Parent{    
  void msg()throws ArithmeticException {  
    System.out.println("parent method");  
  }    
}    
    
public class TestExceptionChild2 extends Parent{    
  void msg()throws Exception {  
    System.out.println("child method");  
  }    
    
  public static void main(String args[]) {    
   Parent p = new TestExceptionChild2();    
     
   try {    
   p.msg();    
   }  
   catch (Exception e){}   
  
  }    
}     

在这里插入图片描述

subclass overridden method declares same exception

import java.io.*;    
class Parent{    
  void msg() throws Exception {  
    System.out.println("parent method");  
  }    
}    
    
public class TestExceptionChild3 extends Parent {    
  void msg()throws Exception {  
    System.out.println("child method");  
  }    
    
  public static void main(String args[]){    
   Parent p = new TestExceptionChild3();    
     
   try {    
   p.msg();    
   }  
   catch(Exception e) {}    
  }    
}  

在这里插入图片描述

subclass overridden method declares subclass exception

import java.io.*;    
class Parent{    
  void msg()throws Exception {  
    System.out.println("parent method");  
  }    
}    
    
class TestExceptionChild4 extends Parent{    
  void msg()throws ArithmeticException {  
    System.out.println("child method");  
  }    
    
  public static void main(String args[]){    
   Parent p = new TestExceptionChild4();    
     
   try {    
   p.msg();    
   }  
   catch(Exception e) {}    
  }    
}    

在这里插入图片描述

subclass overridden method declares no exception

import java.io.*;    
class Parent {    
  void msg()throws Exception{  
    System.out.println("parent method");  
  }    
}    
    
class TestExceptionChild5 extends Parent{    
  void msg() {  
    System.out.println("child method");  
  }    
    
  public static void main(String args[]){    
   Parent p = new TestExceptionChild5();    
     
   try {    
   p.msg();    
   }  
   catch(Exception e) {}  
       
  }    
}     

在这里插入图片描述

10.What is exception propagation?

  • An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack.
  • This procedure is called exception propagation.
  • By default, checked exceptions are not propagated.
class TestExceptionPropagation1{  
  void m(){  
    int data=50/0;  
  }  
  void n(){  
    m();  
  }  
  void p(){  
   try{  
    n();  
   }catch(Exception e){System.out.println("exception handled");}  
  }  
  public static void main(String args[]){  
   TestExceptionPropagation1 obj=new TestExceptionPropagation1();  
   obj.p();  
   System.out.println("normal flow...");  
  }  
}  

在这里插入图片描述

在这里插入图片描述

  • In the above example exception occurs in the m() method where it is not handled, so it is propagated to the previous n() method where it is not handled, again it is propagated to the p() method where exception is handled.
  • Exception can be handled in any method in call stack either in the main() method, p() method, n() method or m() method.
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java