Java exception Interview Questions and Answers

Java and provides a robust object-oriented methods to handle called Java exception handling abnormal situation.

What the 1. Java exceptions are?

Is an exception error events that may occur during program execution, it will destroy its normal flow. Abnormalities may result from a variety of situations, such as wrong data input by the user, hardware failure, network connection failure.

Any errors that occur when executing Java statements whenever, creates an exception object, then JRE tries to find an exception handler to handle the exception. If appropriate exception handler is found, the object is passed to the exception handler code to handle the exception, it referred to catch exceptions . If the handler is not found, the application will throw an exception to the runtime environment, JRE and terminate the program.

Java exception handling framework only for error, exception handling framework does not deal with the compiler handle runtime errors.

What exception handling keywords 2.Java that?

java exception handling uses four keywords.

  1. the throw : Sometimes we definitely want to create an exception object and then thrown to stop the normal processing procedures. throw keyword is used to throw a runtime exception processing.

  2. throws : When we throw any exceptions checked in the method and will not be processed, we need to use the throws keyword in the method signature, so that the caller know that the program will throw an exception. The caller ways to deal with these exceptions, you can use throwskeywords to propagate it to its caller method. We can provide a plurality of abnormality in the throws clause, and it can also be main () used with the method.

  3. try-catch : We use the try-catch block exception handling code. try block is started, the catch is at the end of the try block, the processing for abnormality. We can try to capture a plurality of catch blocks, and try-catch block can also be nested. Exception catch block requires a parameter of type should be.

  4. the finally : the finally block is optional, only with the try-catch block. Due to abnormal pauses execution process, so we could open some of the resources will not be closed, so you can use the finally block. Whether or not an exception occurs, finally block will always be executed.

    3. Explain the Java exception hierarchy?

    Java exceptions are hierarchical, inheritance used to classify different types of exceptions. ThrowableIs the father of Java class hierarchy of exceptions, it has two sub-objects - Errorand Exception. When abnormalities and abnormal operation further divided into abnormal.

Error is a special case beyond the scope of the application, and recover from unforeseen, such as hardware failure, JVM crash or memory error.

Checked Exception is that we can expect an abnormal situation and try to recover from the program in the program, such as FileNotFoundException. We should catch the exception, and provide users with useful information, and properly recorded for debugging. ExceptionAll "checked exception," the parent class.

Runtime Exception was caused by incorrect programming, for example, attempts to retrieve the elements from the Array. Before attempting to retrieve elements, we should first check the length of the array, otherwise it may ArrayIndexOutOfBoundExceptionbe thrown at run time. RuntimeExceptionAbnormal parent class for all runtime.

What is important is the method 4.Java exception class?

None Exception and all subclasses provide any particular method, and all the methods are defined in the base class Throwable.

  1. The getMessage String () - This method returns a string Throwable message, and may provide the message when abnormality by creating its constructor.
  2. The getLocalizedMessage String () - This method provides for a subclass can override it to provide a locale-specific message to the calling program. Throwable class implementation of this method using only getMessage()a method to return the exception message.
  3. the Throwable getCause the synchronized () - This method returns null or cause of abnormality (the reason is unknown).
  4. ToString String () - This method returns a String Throwable information about the format, and returns the String containing the name of the class Throwable localized message.
  5. printStackTrace void () - This method will stack trace information printed on the standard error stream, this method has been overloaded, we can pass PrintStream or PrintWriter as parameters to the stack trace information is written to the file or stream.

    5. Explain Java 7 ARM Feature capture and multi-block?

    If you catch a lot of abnormalities in a single try block, you will notice that the catch block code looks very ugly, and consists of redundant code is used to record the wrong composition, remember that one of the functions of Java 7 is more we capture block may capture a plurality of abnormality in a single catch block. catch block having this function is as follows:

catch(IOException | SQLException | Exception ex){
     logger.error(ex);
     throw new MyException(ex.getMessage());
}

In most cases, we use a finally block just to close the resource, we sometimes forget to turn them off and get run when resources are exhausted exception. These abnormalities difficult to debug, we may need to investigate each location using this type of resource to ensure that we turn it off. Therefore, one improvement java 7 is try-with-Resources , we can create a resource in the try statement itself, and use it in a try-catch block. When the execution from the try-catch block, the runtime environment will automatically turn off these resources. Try-catch block as an example of such an improved:

try (MyResource mr = new MyResource()) {
    System.out.println("MyResource created in try-with-resources");
} catch (Exception e) {
    e.printStackTrace();
}

6.Java in Checked and Unchecked abnormal What is the difference?

1, abnormalities should use try-catch block is processed in the code, otherwise the method should be used so that the caller knows the keyword throws checked exceptions which might be thrown. Unchecked exception does not require processing in the program, you do not need to be mentioned in the throws clause of the method.

2., Exception is the superclass of all Checked abnormal, but RuntimeExceptionare all Unchecked exception superclass. Please note, RuntimeException is a subclass of Exception.

3, Checked exceptions are needed program error handling in your code, or you will get a compile-time error. For example, if you use a FileReader to read the file, the file may be thrown FileNotFoundException, we must be captured in a try-catch block or throw it again to the caller method. Unchecked exceptions are usually caused by poor programming, for example, in the method invocation object reference and not sure it is not null, the cause NullPointerException. For example, I could write a way to remove all the vowels in the string. Ensure that the object does not pass an empty string is the responsibility of the caller. I might change the approach to these situations, but ideally, the caller should be aware of this.

What is the difference between 7.Java the throw and throws that?

Use the keyword throws and methods together to declare that the method may throw an exception, and throw keyword is used to interrupt the program flow, processing and exception object when handed over to run.

8. How to write a custom exception with Java?

We can extend Exceptionthe class or any subclass it to create our custom exception class. Custom exception class may have its own variables and methods can be used to transfer error code or other information associated with the abnormality to the exception handler.

A simple example is shown below custom exception.

package com.journaldev.exceptions;

import java.io.IOException;

public class MyException extends IOException {

    private static final long serialVersionUID = 4664456874499611218L;
    
    private String errorCode="Unknown_Exception";
    
    public MyException(String message, String errorCode){
        super(message);
        this.errorCode=errorCode;
    }
    
    public String getErrorCode(){
        return this.errorCode;
    }
    

}

9. What is in Java OutOfMemoryError?

In Java OutOfMemoryError is a subclass of java.lang.VirtualMachineError when JVM heap memory is insufficient, it will be thrown JVM. We can resolve this error by modifying the java option provides more memory.

$>java MyProgram -Xms1024m -Xmx1024m -XX:PermSize=64M -XX:MaxPermSize=256m

10. What are the different circumstances lead to the "main thread exception"?

Some common thread main exceptions are:

  • main thread java.lang.UnsupportedClassVersionError anomaly : When your Java JDK classes from another version of the compiler, and you try to run it from another version of Java, this exception will occur.
  • main thread java.lang.NoClassDefFoundError anomaly : There are two variants of this exception. The first is to provide you with the full name of the class position. Class extension. The second case is when the class can not be found.
  • main thread java.lang.NoSuchMethodError an exception : When you try to run does not have a main method of the class, this exception will occur.
  • main thread java.lang.ArithmeticException an exception : whenever any exception is thrown from the main method, it will print console exception. The first section describes the main method throws exception, the second portion of the print exception class name, then exception message is printed after the colon.

The 11.Java final, finally and finalize what is the difference?

final and finally are Java keywords, and finalize a method.

  • The final keyword class variables may be used together so that they can not be reassigned; class by class extend avoided; final
    keyword can be covered with the method avoids subclasses;

  • finally keyword can be used with the try-catch block to provide the statement is always executed even if there is some abnormal, usually will eventually be used to close the resource.

  • finalize () method is executed by the garbage collector before the object is destroyed, it is sure to close all the global resources of a good way.

Of the three, only finally exception handling related to Java.

12. What happens when the main method throws an exception?

When the main () method throws an exception, Java Runtime to terminate the program and print the exception message and stack trace in the system console.

13. We may have an empty catch blocks it?

We can have an empty catch blocks, but this is the worst programming examples. We should never empty catch block, the block because if the exception is captured, we will not have information about the exception, debug it is a nightmare. There should be at least a logging statements to the exception details recorded in the console or log file.

14. provide some Java exception handling best practices it?

Some of the best practices related to the Java exception handling is:

  • Capture specific abnormalities can simplify debugging.
  • In the program throws an exception (Fast-Fast) as soon as possible.
  • In the latter part of the program to catch the exception, let the caller handle exceptions.
  • Use Java 7 ARM feature to ensure that resources are shut down, or use the finally block to close them properly.
  • Always record exception message for debugging.
  • Using multiple catch blocks to make the code more clean.
  • Use custom exception can be caused by a single type of exception from the application API.
  • Follow the naming convention, always ending Exception.
  • Javadoc @throws recording using the abnormality caused by the process.
  • Abnormal costly, so it makes sense only when an exception is thrown. Otherwise, you can capture them and return null or not responding.

15. The following procedures What is the problem, how do we solve?

Here, we will examine some programming issues associated with abnormalities of Java.

1). The following procedures What is the problem?

package com.journaldev.exceptions;

import java.io.FileNotFoundException;
import java.io.IOException;

public class TestException {

    public static void main(String[] args) {
        try {
            testExceptions();
        } catch (FileNotFoundException | IOException e) {
            e.printStackTrace();
        }
    }

    public static void testExceptions() throws IOException, FileNotFoundException{
        
    }
}

The above does not compile, and you receive an error message, "The exception FileNotFoundException is already caught by the alternative IOException". This is because a subclass of IOException FileNotFoundException is, there are two ways to resolve this problem.

The first method is to use a single two abnormal catch block.

try {
    testExceptions();
}catch(FileNotFoundException e){
    e.printStackTrace();
}catch (IOException  e) {
    e.printStackTrace();
}

Another method is to remove from FileNotFoundException capture more blocks.

try {
    testExceptions();
}catch (IOException  e) {
    e.printStackTrace();
}

You can choose either method according to the situation.

2). The following program What is the problem?

package com.journaldev.exceptions;

import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.bind.JAXBException;

public class TestException1 {

    public static void main(String[] args) {
            try {
                go();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (JAXBException e) {
                e.printStackTrace();
            }
    }

    public static void go() throws IOException, JAXBException, FileNotFoundException{
        
    }
}

The program will compile error, because FileNotFoundException is a subclass of IOException, FileNotFoundException catch block and therefore inaccessible, and you receive the error message "Unreachable catch block for FileNotFoundException. It is already handled by the catch block for IOException".

You need to fix the catch block order to solve this problem.

try {
    go();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch (JAXBException e) {
    e.printStackTrace();
}

Note, JAXBException or not associated with IOException FileNotFoundException, the catch block may be placed in the hierarchy than any position.

3). The following program What is the problem?

package com.journaldev.exceptions;

import java.io.IOException;

import javax.xml.bind.JAXBException;

public class TestException2 {

    public static void main(String[] args) {
        try {
            foo();
        } catch (IOException e) {
            e.printStackTrace();
        }catch(JAXBException e){
            e.printStackTrace();
        }catch(NullPointerException e){
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void foo() throws IOException{
        
    }
}

The program will not compile because JAXBException is a checked exception, and foo () method should throw this exception to capture the calling method. You will receive the error message "capture block JAXBException inaccessible. This does not throw an exception from the try statement body.

To resolve this problem, you will have to delete JAXBException catch block.

Note that capture NullPointerException is effective because it is unchecked exceptions.

4). The following program What is the problem?

package com.journaldev.exceptions;

public class TestException3 {

    public static void main(String[] args) {
        try{
        bar();
        }catch(NullPointerException e){
            e.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
        
        foo();
    }

    public static void bar(){
        
    }

    public static void foo() throws NullPointerException{
        
    }
}

This is a tricky question, the code is no problem, it will compile successfully. We can always capture the Exception or any unchecked exception, even if it is not in the throws clause of the method as well.

Similarly, if the method (foo) statement unchecked exceptions in the throws clause, then handle the exception is not mandatory in the program.

5). The following program What is the problem?

package com.journaldev.exceptions;

import java.io.IOException;

public class TestException4 {

    public void start() throws IOException{     
    }

    public void foo() throws NullPointerException{
        
    }
    }

    class TestException5 extends TestException4{

    public void start() throws Exception{
    }

    public void foo() throws RuntimeException{
        
    }
}

The above program can not compile because different sub-classes start () method signature. To resolve this problem, we can subclass method characteristic change, you can also delete the throws clause from the subclass and superclass method is identical, as shown below.

@Override
public void start(){
}

6). The following program What is the problem?

package com.journaldev.exceptions;

import java.io.IOException;

import javax.xml.bind.JAXBException;

public class TestException6 {

    public static void main(String[] args) {
        try {
            foo();
        } catch (IOException | JAXBException e) {
            e = new Exception("");
            e.printStackTrace();
        }catch(Exception e){
            e = new Exception("");
            e.printStackTrace();
        }
    }

    public static void foo() throws IOException, JAXBException{
        
    }
}

The above program can not compile because multi-capture block exception object is the ultimate target, we can not change its value. As the "unable to allocate multiple capture block parameter e", a compile-time error.

We must remove the "e" assigned to the new exception object to resolve this error.


"A short step, a thousand miles," hope in the future you can: have a dream horse habitat everywhere! Come on, Junior!

No public concern: "Java confidant" , updated daily Java knowledge Oh, look forward to your arrival!

  • Send " Group ", progress with 100,000 programmers.
  • Send " interview " to receive information BATJ interview, video interview Raiders.
  • Send " Fun algorithm " to receive "Fun algorithm" series of video tutorials.
  • Do not send " 1024 " ...

Guess you like

Origin www.cnblogs.com/java-friend/p/11775823.html