In the Java Core Knowledge interview, you can always encounter questions about handling exception and error. Exception processing is a very important aspect of Java application development and the key to writing robust and stable Java programs, which naturally makes it a frequent part of the interview. The interview questions about error and exception in Java are about the concept of exception and error, how to deal with exception, and the best practices to be followed when dealing with exception, and more. Although questions about multithreading, garbage collection, JVM concepts, and object-oriented design still dominate this type of interview, you still need to be prepared to answer "how to deal with errors effectively". Some interviewers also test the programmer's debugging skills, because fast handling of exceptions is another important Java programming technique. If a programmer is familiar with classnotfoundexception or outofmemoryerror that are uncommon and difficult to handle, chances are that he has a good combat experience. In this article, we will see some questions about Java error and exception in Java EE interview, beginner, experienced, and advanced Java developers.
Exception and error interview questions in Java the following is a personal summary of the knowledge of exception and error that I have often been asked in the interview by Java and EE developers. While sharing my answers, I also made quick revisions to these questions and provided the source code for in-depth understanding. I summed up a variety of difficulty issues, suitable for novice code farmers and advanced Java code farming. If you encounter a problem that is not in my list and this question is very good, please share it in the comments below. You can also share in the comments that you answered the wrong question during the interview.
1) What is exception in Java?
This question is often asked when the first question is about an anomaly or when you're interviewing a rookie. I have never met a senior or senior engineer when someone asked this thing, but for the rookie, is very willing to ask this. In simple terms, exceptions are the way that Java communicates to your system and program errors. In Java, exception functionality is achieved by implementing classes such as Throwable,exception,runtimeexception, and then some keywords that deal with exceptions, such as Throw,throws,try,catch, Finally, something like that. All anomalies are derived from throwable. Throwable further divides the error into java.lang.Exception and Java.lang.Error. Java.lang.Error is used to handle system errors, such as Java.lang.StackOverFlowError or Java.lang.OutOfMemoryError. The exception is then used to handle program errors, the requested resource is not available, and so on.
2) What is the difference between check and non-checked exceptions in Java?
This is another very popular Java Anomaly interview, which will appear at various levels of Java interviewing. The main difference between check-type and non-checked exceptions is the way they are handled. Check-type exceptions require the use of try, catch and finally keywords to be processed at compile time, or the compiler will error. You do not need to do this for non-checked exceptions. All exceptions in Java that inherit from the Java.lang.Exception class are check-type exceptions, and all exceptions that inherit from RuntimeException are referred to as non-checked exceptions. You can also check out the next article to learn more about the differences between checked and non-checked exceptions.
3) What's the similarities between NullPointerException and Arrayindexoutofboundexception in Java?
This is not a very popular issue in Java exception interviews, but it can be seen at different levels of beginner interviews to test candidates ' familiarity with the concept of check-and non-checked anomalies. By the way, the answer to this question is that both exceptions are non-check exceptions and are inherited from RuntimeException. This problem may lead to another problem, that is, what is different about the array of Java and C, because the arrays in C are not size-constrained and will never throw arrayindexoutofboundexception.
4) in the process of Java exception handling, what are the best practices you follow?
This question is a very common problem in interviewing technical managers. Because exception handling is critical in project design, it is necessary to be proficient in exception handling. There are a number of best practices for exception handling, as outlined below, which improve the robustness and flexibility of your code:
1) Returns a Boolean value when invoking a method instead of returning null, which can be nullpointerexception. Since the null pointer is the most disgusting exception in Java exceptions, you can refer to the following technical article coding best practices to minimize nullpointerexception. Take a look at the concrete examples inside.
2) do not write code in the catch block. An empty catch block is an error event in exception handling because it catches only exceptions without any processing or prompting. Usually you have to print out the exception information, of course, you'd better deal with the exception information according to the requirements.
3) can throw the controlled anomaly (checked Exception) and try not to throw away the non-controlled anomaly (checked Exception). By removing duplicate exception handling code, you can improve the readability of your code.
4) Never let your database-related exceptions appear to the client. Since the vast majority of databases and SqlException exceptions are controlled exceptions, in Java you should handle exceptions in the DAO layer and return to the processed exception information that allows the user to understand and correct the action based on the exception prompt.
5) in Java, be sure to call the close () method in the finally block after the database connection, database query, and stream processing. I have shared a lot of knowledge about this in my article top Java exception handling best practices, and you can also look at this article.
5) Since we can use runtimeexception to handle errors, why do you think there is a check-type exception in Java ?
This is a controversial issue and you should be careful when answering the question. Although they would certainly like to hear your point of view, they are most interested in convincing reasons. I think one of the reasons is that the existence of an inspection anomaly is a design decision that is influenced by the experience of programming language design that is older than Java, such as C + +. The vast majority of check-type exceptions are in the Java.io package, which is reasonable, because a strong program must gracefully handle this situation when you request a system resource that does not exist. By declaring IOException as a check-type exception, Java ensures that you can gracefully handle exceptions. Another possible reason is that you can use catch or finally to ensure that a limited number of system resources (such as file descriptors) are released as soon as you use them. Joshua Bloch wrote the effective Java book in many places involved in this topic, it is worth reading.
6) What is the difference between a throw and a throws two keywords in Java?
An interview question that a Java beginner should master. The throw and throws at first glance look very similar, especially when you are a Java beginner. Although they look similar, they are used when dealing with anomalies. But the use of the code and the place is different. Throws always appears in a function header to indicate the various exceptions that the member function might throw, and you can declare an unchecked exception, but this is not mandatory by the compiler. If the method throws an exception then call this method to handle the exception. Another keyword throw is used to throw arbitrary exceptions, and by the syntax you can throw arbitrary throwable (i.e. throwable or any throwable derived class), throw can interrupt the program to run, so it can be used instead of return. The most common example is to throw the Unsupportedoperationexception code with a throw in an empty method where return is required:
?
123 |
private static void show() { throw new UnsupportedOperationException( "Not yet implemented" ); } |
7) What is an "anomaly chain"?
The "anomaly chain" is a very popular exception handling concept in Java, which means that another exception is thrown when an exception is handled, resulting in an exception chain. This technique is mostly used to encapsulate "checked exceptions" (checked exception) into "Unchecked exceptions" (unchecked exception) or runtimeexception. By the way, if you decide to throw a new exception because of the exception, you must include the original exception so that the handler can access the root cause of the exception through the Getcause () and Initcause () methods.
8) Have you ever custom implemented an exception? How did you write that?
Obviously, most of us have written custom or business anomalies like accountnotfoundexception. The main reason to ask this Java exception question during an interview is to find out how you are using this feature. This can be more accurate and refined to deal with anomalies, of course, it is also related to your choice of checked or unchecked exception. By creating a specific exception for each particular situation, you provide a better choice for the caller to handle the exception better. I prefer more precise exceptions than general exception. Creating a large number of custom exceptions increases the number of project classes, so maintaining a balance between custom exceptions and common exceptions is the key to success.
9) What changes have been made to exception handling in JDK7?
This is a recent new Java exception handling question. The main new additions to error and exception (Exception) processing in JDK7 include the addition of more than 2 exceptions in a catch block, as if multiple catch blocks were used. The other is automated resource management (ARM), also known as Try-with-resource block. All of these 2 features reduce the amount of code while handling exceptions while improving the readability of your code. Understanding these features not only helps developers write better code for exception handling, but also makes you more prominent in the interview. I recommend reading Java 7 to get a deeper understanding of these 2 very useful features.
10) Have you ever met a OutOfMemoryError error? How did you manage that?
This question will be used when interviewing senior programmers and the interviewer wants to know how you handled this dangerous outofmemoryerror error. It must be admitted that no matter what project you do, you will encounter this problem. So if you say you haven't met, the interviewer won't buy it. If you are not familiar with this problem, even if you have not met, and you have 3 or 4 years of Java experience, then ready to deal with this problem. While answering this question, you can also take the opportunity to show the interview your skills in dealing with memory leaks, tuning, and debugging. I find that people who have mastered these techniques can impress the interviewer. You can also go to "How to fix Java.lang.OutOfMemoryError" to see another article I wrote about this issue in more detail
11) If the method returns a result before the finally code block is executed, or if the JVM exits, will the code in the finally block execute?
The question can also be asked in a different way: "If System.exit () is called in a try or finally code block, what will be the result". Knowing how the finally block is executed, even if the try has already used the return returned result, is valuable for understanding Java's exception handling. The code in the finally block will not execute unless there is system.exit (0) to exit the JVM in the try.
12) The difference between final,finalize,finally keywords in Java
This is a classic Java interview question. One of my friends asked this question for Morgan Stanley's core Java developer for telecommunications. Final and finally are the Java keywords, and finalize is the method. The final keyword is useful when creating immutable classes, just declaring that the class is final. The Finalize () method is called by the garbage collector before it reclaims an object, but there is no guarantee that this method will be called in the Java specification. The finally keyword is the only keyword that is related to exception handling that is discussed in this article. In your product code, the finally block must be used when closing the connection and resource files. See more here
13) What is wrong with the following code:
?
1234567891011121314 |
public
static
void
start()
throws
IOException, RuntimeException{
throw new
RuntimeException(
"Not able to Start"
);
}
public
static
void
main(String args[]) {
try
{
start();
}
catch
(Exception ex) {
ex.printStackTrace();
}
catch
(RuntimeException re) {
re.printStackTrace();
}
}
|
This code throws a compile exception error in the RuntimeException type variable "Re" that catches the exception code block. Because exception is a superclass of runtimeexception, all runtimeexception in the Start method are captured by the first catch exception block, so that the second catch block cannot be reached, which is thrown "exception java.lang.RuntimeException has already been caught"The reason for the compilation error.
) what are the following Java code errors:
?
1234567891011 |
public
class
SuperClass {
public
void
start()
throws IOException{
throw
new
IOException(
"Not able to open file"
);
}
}
public
class
SubClass
extends
SuperClass{
public
void
start()
throws
Exception{
throw
new
Exception(
"Not able to start"
);
}
}
|
This code compiler is dissatisfied with overwriting the Start method with a subclass. Because the overrides of methods in each Java are regular, an overridden method cannot throw an exception that is higher than the original method inheritance. Because the Start method here throws a ioexception in the superclass, all the start methods in the subclass can only be thrown either by ioexcepition or its subclasses, but not by its superclass, such as exception.
15) What is wrong with the following Java exception code:
?
1234567891011 |
public
static
void
start(){
System.out.println(
"Java Exception interivew question Answers for Programmers"
);
}
public static
void
main(String args[]) {
try
{
start();
}
catch
(IOException ioe){
ioe.printStackTrace();
}
}
|
In the Java exception example code above, the compiler will handle the IOException times wrong, because IOException is subject to a check exception, and the Start method does not throw IOException, so the compiler throws an "exception, Java.io.IOException does not throw in the body of the try statement, but if you change IOException to exception, the compiler error will disappear because exception can be used to catch all runtime exceptions, so there is no need to declare the throw statement. I like this confusing Java exception interview, because it doesn't make it easy to find out whether it's IOException or exception. You can also find some confusing questions about Java errors and exceptions in the Java puzzles of Joshua Bloach and Neil Gafter.
I also often see face questions about Java errors and anomalies encountered in some new and experienced Java interviewers. Of course there are a lot of questions about the exception that I did not relate to, and if you have some good questions, please let me know and I will try to include these questions in this Java exception question and answer series. And the last question I left to my buddies was, "Why are Java exceptions considered better than returning error codes?" Tell me what you think about the Java Exception interview series here.
Java Exception interview Common topics