Java interview questions - exceptions

王林
Release: 2020-12-10 16:38:05
forward
3713 people have browsed it

Java interview questions - exceptions

java interview questions exceptions

The interview questions are as follows:

1. What are exceptions in Java?

Exceptions are error events that may occur during the execution of a program and interrupt its normal flow. Exceptions may arise from different types of situations such as incorrect data entered by the user, hardware failure, network connection failure, etc.

(Learning video sharing: java teaching video)

Whenever any error occurs when executing a java statement, an exception object will be created, and then the JRE will try to find exception handling program to handle exceptions. If a suitable exception handler is found, the exception object is passed to the handler code to handle the exception, which is called catching the exception. If the handler is not found, the application throws an exception to the runtime environment and the JRE terminates the program.

The Java exception handling framework is only used to handle runtime errors. Compile time errors are not handled by the exception handling framework.

2. What is the exception handling keyword in Java?

Four keywords are used in java exception handling.

throw: Sometimes we explicitly create an exception object and then throw it to stop the normal processing of the program. The throw keyword is used to throw an exception to the runtime to handle it.

throws: When we throw any checked exception in a method without handling it, we need to use the throws keyword in the method signature to let the caller program know the exceptions that may be thrown by the method. The calling method can handle these exceptions or propagate them to its calling method using the throws keyword. We can provide multiple exceptions in throws clause and also with main() method.

try-catch: We use try-catch blocks in the code for exception handling. try is the beginning of the block, and catch handles the exception at the end of the try block. We can have multiple catch blocks using try, and try-catch blocks can also be nested. The catch block requires a parameter which should be of type Exception.

finally: The finally block is optional and can only be used in try-catch blocks. Since exceptions pause the execution process, we may open some resources that will not be closed, so we can use finally block. The finally block is always executed regardless of whether an exception occurs.

3. Explain the Java exception hierarchy?

Java exceptions are hierarchical, and inheritance is used to classify different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects - Error and Exception. Exceptions are further divided into checked exceptions and runtime exceptions.

Errors are special circumstances that are beyond the scope of the application and cannot be predicted and recovered from, such as hardware failure, JVM crash, or out of memory error.

Checked Exceptions are special situations that we can expect and try to recover from in our programs, such as FileNotFoundException. We should catch this exception and provide a useful message to the user and log it properly for debugging. Exception is the parent class of all Checked Exceptions.

Runtime exceptions are caused by incorrect programming, such as trying to retrieve elements from an Array. We should check the length of the array before trying to retrieve elements, otherwise it may throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions.

4. What are the important methods of Java exception class?

Exception and all its subclasses do not provide any specific methods, and all methods are defined in the base class Throwable.

String getMessage() - 此方法返回消息String of Throwable,并且可以在通过构造函数创建异常时提供消息。
String getLocalizedMessage() - 提供此方法,以便子类可以覆盖它以向调用程序提供特定于语言环境的消息。此方法getMessage()的可抛出类实现只是使用方法来返回异常消息。
synchronized Throwable getCause() - 此方法返回异常的原因或null id,原因未知。
String toString() - 此方法以String格式返回有关Throwable的信息,返回的String包含Throwable类和本地化消息的名称。
void printStackTrace() - 此方法将堆栈跟踪信息打印到标准错误流,此方法已重载,我们可以将PrintStream或PrintWriter作为参数传递,以将堆栈跟踪信息写入文件或流。
Copy after login

5. Explain Java 7 ARM features and multi-catch blocks?

If you catch a lot of exceptions in a try block, you will find that the catch block code looks very ugly and mainly consists of redundant code to log errors. Remember that one of the features of Java 7 is multi -catch block. We can catch multiple exceptions in one catch block. A catch block with this functionality looks like this:

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

Most of the time we use finally blocks to close resources, sometimes we forget to close them and get runtime exception when the resource is exhausted. These exceptions are difficult to debug and we may need to look at every place we use this type of resource to make sure we close it. So one of the improvements in java 7 is try-with-resources, we can create a resource in try statement and use it in try-catch block. When execution comes from a try-catch block, the runtime environment automatically closes these resources. A sample try-catch block with this improvement is:

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

(More related interview questions shared: java interview questions and answers)

6. Checked in Java What is the difference between Unchecked Exception?

Checked Exceptions should be handled in code using try-catch blocks, otherwise methods should use the throws keyword to let the caller know about checked exceptions that may be thrown from the method. Unchecked exceptions do not need to be handled in the program or mentioned in the throws clause of the method.

Exception is the superclass of all checked exceptions RuntimeException, but the superclass of all unchecked exceptions. Please note that RuntimeException is a subclass of Exception.

已检查的异常是需要在代码中处理的错误方案,否则您将收到编译时错误。例如,如果您使用FileReader读取文件,它会抛出FileNotFoundException,我们必须在try-catch块中捕获它或将其再次抛给调用方法。

未经检查的异常主要是由编程不良引起的,例如在对象引用上调用方法时的NullPointerException,而不确保它不为null。例如,我可以编写一个方法来从字符串中删除所有元音。确保不传递空字符串是调用者的责任。我可能会改变方法来处理这些场景,但理想情况下,调用者应该处理这个问题。

7、Java中throw和throws关键字有什么区别?

throws关键字与方法签名一起用于声明方法可能抛出的异常,而throw关键字用于破坏程序流并将异常对象移交给运行时来处理它。

8、如何在Java中编写自定义异常?

我们可以扩展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;
}
}
Copy after login

9、Java中的OutOfMemoryError是什么?

Java中的OutOfMemoryError是java.lang.VirtualMachineError的子类,当JVM用完堆内存时,它会抛出它。我们可以通过提供更多内存来通过java选项运行java应用程序来修复此错误。

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

10、“主线程中的异常”有哪些不同的情况?

一些常见的主线程异常情况是:

主线程java.lang.UnsupportedClassVersionError中的异常:

当您的java类是从另一个JDK版本编译并且您尝试从另一个Java版本运行它时,会出现此异常。

主线程java.lang.NoClassDefFoundError中的异常:

此异常有两种变体。第一个是您提供类全名和.class扩展名的地方。第二种情况是找不到Class。

主线程java.lang.NoSuchMethodError中的异常:

main:当您尝试运行没有main方法的类时会出现此异常。

线程“main”中的异常java.lang.ArithmeticException:

每当从main方法抛出任何异常时,它都会打印异常是控制台。第一部分解释了从main方法抛出异常,第二部分打印异常类名,然后在冒号后打印异常消息。

11、Java中的final,finally和finalize有什么区别?

final和finally是java中的关键字,而finalize是一种方法。

final关键字可以与类变量一起使用,以便它们不能被重新分配,类可以避免按类扩展,并且使用方法来避免子类覆盖。

finally关键字与try-catch块一起使用,以提供始终执行的语句即使出现一些异常,通常最终也会用来关闭资源。

finalize()方法由垃圾收集器在销毁对象之前执行,这是确保关闭所有全局资源的好方法。

在三者之中,最后只涉及到java异常处理。

12、当main方法抛出异常时会发生什么?

当main()方法抛出异常时,Java Runtime终止程序并在系统控制台中打印异常消息和堆栈跟踪。

13、我们可以有一个空的catch块吗?

我们可以有一个空的catch块,但它是最差编程的例子。我们永远不应该有空的catch块,因为如果异常被该块捕获,我们将没有关于异常的信息,并且它将成为调试它的噩梦。应该至少有一个日志记录语句来记录控制台或日志文件中的异常详细信息。

14、提供一些Java异常处理最佳实践?

与Java异常处理相关的一些最佳实践是:

使用特定异常以便于调试。

在程序中尽早抛出异常(Fail-Fast)。

在程序后期捕获异常,让调用者处理异常。

使用Java 7 ARM功能确保资源已关闭或使用finally块正确关闭它们。

始终记录异常消息以进行调试。

使用multi-catch块清洁关闭。

使用自定义异常从应用程序API中抛出单一类型的异常。

遵循命名约定,始终以Exception结束。

记录在javadoc中使用@throws的方法抛出的异常。

异常是昂贵的,所以只有在有意义的时候抛出它。否则,您可以捕获它们并提供空或空响应。

相关推荐:java入门教程

The above is the detailed content of Java interview questions - exceptions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!