Interview questions 1--java exception and error face questions 10 Ask 10 answer __java

Source: Internet
Author: User
Tags exception handling finally block garbage collection throwable java keywords

English Original: Java Exception and Error interview Questions Answers

In the Java Core Knowledge interview, you 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 guest in interview questions. The interview topics about error and exception in Java are mostly about the concept of exception and error, how to deal with exception, and the best practices to follow when dealing with exception, and so on. While issues such as multithreading, garbage collection, JVM concepts, and object-oriented design still dominate such interviews, you still need to be prepared to answer "how to handle errors effectively". Some interviewers also test the programmer's debugging skills, because handling exceptions quickly is another important Java programming technique. If a programmer is familiar with classnotfoundexception or outofmemoryerror that are uncommon and difficult to deal with, chances are that he has a good experience in combat. In this article, we'll see some of the questions about Java error and exception that beginners, experienced and advanced Java developers will be asked for during the Java EE interview.

Exception and error interview questions in Java The following are my personal knowledge of exception and error that are frequently asked in Java and EE developers during interviews. In sharing my answers, I also made quick revisions to these questions and provided the source code for a deeper understanding. I have summed up a variety of difficult issues, suitable for novice code farmers and advanced Java code farmers. If you encounter a problem that is not in my list, and the problem is very good, please share it in the comments below. You can also share in the comments that you answered incorrectly during the interview.

1 What is the exception in Java?

This question is often asked when you first ask about the abnormality or when you are 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 short, exceptions are the way that Java communicates to you about systems and programs that are wrong. In Java, the exception function is to implement classes such as Throwable,exception,runtimeexception, and then some keywords to deal with anomalies, such as Throw,throws,try,catch, Finally and the like. All the 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. Exception is then used to handle program errors, the requested resources are not available, and so on.

2 What is the difference between the check-type exception and the unchecked exception in Java.

This is also a very popular Java exception interview problem, will appear in various levels of Java interview. The main differences between check-type and unchecked-type exceptions lie in how they are handled. Check-type exceptions need to be processed at compile time using try, catch, and finally keywords, or the compiler will complain. 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 inherited from runtimeexception exceptions are called non-checked exceptions. You can also look at the next article to learn more about the difference between check-type and unchecked-type exceptions.

3 The similarities between NullPointerException and Arrayindexoutofboundexception in Java.

This is not a very popular problem in the Java exception interview, but it will appear at different levels of beginner interviews to test candidates for familiarity with the concepts of check-and-check-type exceptions. By the way, the answer to this question is that both of these anomalies are both runtimeexception and inherited from the same form. This issue may lead to another problem, that is, the Java and C arrays are different, because the array in C is not the size limit, never throw arrayindexoutofboundexception.

4 What are the best practices you follow in the process of Java exception handling?

This question is a very common problem in interviewing technical managers. Because exception handling is critical in project design, it is essential to be proficient in exception handling. There are many best practices for exception handling, which are listed below, which improve the robustness and flexibility of your code:

1 Returns a Boolean value when invoking the method instead of returning null, which can be nullpointerexception. Because the null pointer is the most disgusting exception in the Java exception, you can refer to the following technical article coding best practices to minimize nullpointerexception. Take a look inside the concrete example.

2 Do not write code in the catch block. An empty catch block is an error event in exception handling because it captures only the exception without any processing or prompting. Usually you have to print out the exception information at least, of course, you'd better deal with the exception information according to the requirement.

3) can throw the controlled anomaly (checked Exception) as far as possible not to be thrown by the non-controlled exception (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 most of the database and SqlException exceptions are controlled exceptions, in Java, you should handle the exception information in the DAO layer, and then return the processed exception message that the user can read and correct the action according to the exception prompt.

5 in Java, be sure to call the close () method in the finally block after database connection, database query, stream processing. I've shared a lot of knowledge about this in my article top Java exception handling best practices, and you can also read this article.

5 If we can use runtimeexception to handle errors, then why do you think there are check-type exceptions 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 for this is that a check-type exception is a design decision that is influenced by the design experience of programming languages earlier than Java, such as C + +. Most check-type anomalies are in the package, which makes sense, because a strong program must be able to handle the situation gracefully when you request a non-existent system resource. 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 written in the effective Java book in a number of topics involved in the topic, it is worth reading.

6 What is the difference between the two keywords throw and throws in Java?

An interview question that a Java beginner should master. Throw and throws look very similar at first glance, especially when you are a Java beginner. Although they look similar, they are used when dealing with anomalies. But the way you use it in your code is different from where you used it. Throws always appears in a function header to indicate the various exceptions that the member function may throw, and you can declare an unchecked exception, but this is not a compiler coercion. If the method throws an exception, then it needs to be handled when the method is called. Another keyword, throw, is used to throw arbitrary exceptions, in which you can throw arbitrary throwable (i.e. throwable or any throwable derived class), throw can interrupt the program and therefore can be used instead of return. The most common example is to use throw to throw unsupportedoperationexception code in a null method where a return is required:?

1 2 3 private static void Show () {throw new unsupportedoperationexception (' not yet implemented '); }
Take a look at this article to see more differences in Java for these two keywords.

7 What is the "abnormal chain"?

The exception chain is a very popular exception handling concept in Java, which is to throw another exception when an exception is handled, resulting in an abnormal chain. Most of the technology is used to encapsulate "checked exceptions" (checked exception) as "Unchecked exceptions" (unchecked exception) or runtimeexception. By the way, if you decide to throw a new exception because of an exception, you must include the original exception so that the handler can access the final source of the exception through the Getcause () and Initcause () methods.

8 Have you ever customized to implement an exception? How do 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 the interview process is to find out how you can use this feature. This can be more accurate and exquisite to deal with the anomaly, of course, this also with you choose checked or unchecked exception closely related. By creating a specific exception for each particular situation, you provide a better choice for the caller to handle the exception better. I prefer a more accurate exception than a generic exception (general exception). Creating a large number of custom exceptions increases the number of project classes, so maintaining a balance between custom exceptions and generic exceptions is the key to success.

9 What changes have been made to exception handling in JDK7.

This is the recently emerging Java exception handling face test. The main new additions to errors (error) and exception (Exception) in JDK7 are 2 features, one in which multiple exceptions can come out of a catch block, just as with multiple catch blocks. The other is automated resource management (ARM), also known as the Try-with-resource block. These 2 features can reduce the amount of code when 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 that you read the Java 7 strategy so that you can get a better understanding of these 2 very useful features.

10 You've had outofmemoryerror mistakes. How did you manage it?

This test will be used when interviewing senior programmers, and the interviewer wants to know how you handled the 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 will definitely not buy it. If you're unfamiliar with the issue, even if you haven't met, and you have 3 or 4 years of Java experience, then be prepared to deal with this problem. While answering this question, you can also take the opportunity to show off your skills in dealing with memory leaks, tuning and debugging. I find that people who master these techniques can impress the interviewer. You can also go to the how to fix java.lang.OutOfMemoryError and see another article I wrote about the more detailed details of this issue

11 If the method returns the result before executing the finally code block, or if the JVM exits, the code in the finally block executes.

This question can also be asked in another way: "What happens if System.exit () is invoked in a try or finally block of code." Knowing how finally blocks are executed, even if the return result is already used in try, is valuable for understanding Java exception handling. The code in the finally block does not execute unless there is a system.exit (0) in the try to exit the JVM.

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 in Telecom. Final and finally are Java keywords, and finalize is the method. The final keyword is useful when creating immutable classes, but declares 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 the method will be invoked in the Java specification. The finally keyword is the only keyword associated with the exception handling discussed in this article. In your product code, finally blocks must be used when closing connections and resource files. See more here

13 What is wrong with the following code:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.