Java exception and error surface question 10 Q 10 Answer

Source: Internet
Author: User
Tags finally block throwable java keywords

In interviews with core knowledge of Java, you can always come up with interview questions about handling Exceptions and Errors. Exception handling 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 visitor in interview questions. The interview questions about Error and Exception in Java are mostly about the concepts of Exception and Error, how to handle Exception, and the best practices to be observed when handling Exception, etc. 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 handle errors effectively". Some interviewers also test programmer debugging skills, because handling exceptions quickly is another important Java programming skill. If a programmer is familiar with the uncommon and difficult ClassNotFoundException or OutOfMemoryError, it is likely that he has good practical experience. In this article, we will see some Java Error and Exception interview questions for beginners, experienced and advanced Java developers during Java J2EE interviews.



Exception and Error Interview Questions in JAVA The following is my personal summary of the knowledge about Exception and Error that Java and J2EE developers often ask during interviews. As I shared my answers, I also quickly revised these questions and provided the source code for deeper understanding. I have summarized various difficulties, suitable for novice code farmers and advanced Java code farmers. If you encounter a problem that is not on my list, and it is very good, please share it in the comments below. You can also share in the comments what you did wrong during the interview.

1) What is Exception in Java?

This question is often asked when first asking about anomalies or when interviewing a novice. I've never asked someone when I met a senior or senior engineer, but for a novice, I'd love to ask this. In simple terms, exceptions are the way Java communicates system and program errors to you. In java, exception functions are implemented by implementing classes such as Throwable, Exception, RuntimeException, and then there are some keywords for handling exceptions, such as throw, throws, try, catch, finally, etc. All exceptions are derived from Throwable. Throwable further divides errors 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. Exceptions are then used to handle program errors, requested resources are not available, and so on.



2) What is the difference between checked and unchecked exceptions in Java?

This is another very popular Java exception interview question that will appear in various levels of Java interviews. The main difference between checked and unchecked exceptions is in how they are handled. Checked exceptions need to be handled at compile time using the try, catch, and finally keywords, otherwise the compiler will report an error. This is not necessary for unchecked exceptions. All exceptions inherited from java.lang.Exception in Java are checked exceptions. All exceptions inherited from RuntimeException are called unchecked exceptions. You can also check out the next article to learn more about the difference between checked and unchecked exceptions.

3) What are the similarities between NullPointerException and ArrayIndexOutOfBoundException in Java?

This is not a very popular question in Java exception interviews, but it will appear in beginner interviews at different levels to test whether candidates are familiar with the concepts of checked and unchecked exceptions. By the way, the answer to this question is that both exceptions are unchecked and both inherit from RuntimeException. This problem may lead to another problem, that is, what is the difference between Java and C arrays, because arrays in C have no size limit, and never throw an ArrayIndexOutOfBoundException.



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

This question is very common in interviewing technical managers. Because exception handling is critical in project design, mastering exception handling is essential. There are many best practices for exception handling. The following list focuses on improving the robustness and flexibility of your code:

1) When calling the method, return a Boolean value instead of returning a null, which can cause a NullPointerException. Since null pointers are the most disgusting exception in Java exceptions, you can refer to the following technical article coding best practices to minimize NullPointerException. Go and see the specific examples inside.

2) Don't write code in the catch block. An empty catch block is an error event in exception handling because it just catches the exception without any handling or prompting. Usually at least you need to print out the exception information, of course, you better deal with the exception information according to your needs.

3) If you can throw a checked exception, try not to throw a checked exception. By eliminating duplicate exception handling code, you can improve the readability of the code.

4) Never let your database related exceptions be displayed to the client. Since most database and SQLException exceptions are controlled exceptions, in Java, you should process the exception information at the DAO layer, and then return the processed exception information that can be understood by the user and correct the operation according to the exception prompt information.

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 10 Java exception handling best practices, and you can also check out this article.


5) Now that we can handle errors with RuntimeException, why do you think there are still checked exceptions in Java?

This is a controversial question and you should be careful when answering it. Although they are definitely willing to hear your point of view, in fact they are most interested in persuasive reasons. I think one of the reasons is that the existence of checked exceptions is a design decision, influenced by the experience of programming languages such as C ++ that are older than Java. Most checked exceptions are in the java.io package, which makes sense, because a robust program must be able to handle this situation gracefully when you request non-existent system resources. By declaring IOException as a checked exception, Java ensures that you can handle exceptions gracefully. Another possible reason is that you can use catch or finally to ensure that a limited amount of system resources (such as file descriptors) are released as soon as possible after you use them. Joshua Bloch's book Effective Java covers this topic in several places and is worth reading.



6) What are the differences between the two keywords throw and throws in java?

A java beginner should master the interview questions. throw and throws look very similar at first, especially if you are a beginner in Java. Although they look similar, they are used when handling exceptions. But the method and place of use in the code are different. throws always appear in a function header to indicate various exceptions that the member function may throw. You can also declare unchecked exceptions, but this is not mandatory by the compiler. If the method throws an exception then you need to handle the exception when calling this method. Another keyword throw is used to throw arbitrary exceptions. According to the syntax, you can throw any Throwable (ie Throwable or any derived class of Throwable). Throw can interrupt the program running, so it can be used instead of return. Use throw to throw UnSupportedOperationException in an empty method where the return is needed:

private static void show () {throw new UnsupportedOperationException ("Not yet implemented");} See this article for more differences between these two keywords in Java. You want paws


7) What is an "exception chain"?

"Exception chain" is a very popular concept of exception handling in Java, which means that another exception is thrown when an exception is processed, which results in an exception chain. This technique is mostly used to encapsulate "checked exception" into "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 ultimate source of the exception through the getCause () and initCause () methods.

8) Have you ever implemented custom exceptions? How to write it?

Obviously, most of us have written custom or business exceptions, like AccountNotFoundException. The main reason to ask this Java exception question during the interview is to discover how you use this feature. This can handle exceptions more accurately and delicately. Of course, this is also related to your choice of checked or unchecked exception. By creating a specific exception for each specific situation, you provide better options for the caller to better handle the exception. I tend to be more precise than general exceptions. Creating a lot of custom exceptions will increase the number of project classes. Therefore, 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 interview question on Java exception handling. In JDK7, two new features are mainly added to Error and Exception handling. One is that multiple exceptions can be generated in a catch block, just like the original use of multiple catch blocks. The other is automated resource management (ARM), also known as a try-with-resource block. Both of these features can reduce the amount of code and improve the readability of the code when handling exceptions. Understanding these features not only helps developers write better exception handling code, but also makes you stand out in the interview. I recommend that you read the Java 7 Raiders so that you can learn more about these two very useful features.

10) Have you encountered an OutOfMemoryError? How did you get it?

This interview question will be used when interviewing senior programmers. The interviewer wants to know how you handled this dangerous OutOfMemoryError. It must be acknowledged that no matter what project you do, you will encounter this problem. So if you say you haven't met it, the interviewer will definitely not buy it. If you are unfamiliar with this problem or haven't even encountered it before 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 the interview to your excellent skills in dealing with memory leaks, tuning and debugging. I find that anyone who masters these techniques can impress the interviewer. You can also go to how to fix java.lang.OutOfMemoryError to see another article I wrote in more detail about this issue



11) If the method returns a result before executing the finally block, or the JVM exits, will the code in the finally block still be executed?

This question can also be asked in another way: "If System.exit () is called in a try or finally block, what will happen?" Understanding how finally blocks are executed, even if return has been used in a try, is very valuable for understanding Java exception handling. The code in the finally block will not execute only if there is System.exit (0) in the try to exit the JVM.

12) The difference between final, finalize, and finally keywords in Java

This is a classic Java interview question. A friend of mine asked this question when recruiting core Java developers in telecommunications for Morgan Stanley. final and finally are Java keywords, while finalize is a method. The final keyword is very useful when creating immutable classes, just to declare that the class is final. The finalize () method is called by the garbage collector before recycling an object, but there is no guarantee in the Java specification that this method will be called. The finally keyword is the only one related to the exception handling discussed in this article. In your production code, you must use the finally block when closing connections and resource files. See more here



13) What are the errors in the following code:
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 compilation exception error in a variable "re" of type RuntimeException that catches the exception code block. Because Exception is a superclass of RuntimeException, all RuntimeExceptions in the start method will be caught by the first catching exception block, so the second catching block cannot be reached, which is throwing "exception java.lang.RuntimeException has already been caught "Cause of compilation error.

14) What are the errors in the following Java code:

 
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 ");}} The compiler will be dissatisfied with subclasses overriding the start method. Because the coverage of each method in Java is regular, the exception that a covered method cannot throw is higher than the original method inheritance relationship. Because the start method here throws an IOException in the superclass, all start methods in the subclass can only throw either IOExcepition or its subclass, but not its superclass, such as Exception. yale8848


15) What's wrong with the following Java exception code:

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 above Java exception example code, the compiler will report an error when handling IOException, because IOException is a checked exception, and the start method does not throw IOException, so the compiler will throw "Exception, java.io.IOException will not Throw in the try statement body ", 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 question, because it will not make it easy to find out whether it is an IOException or an Exception. You can also find some confusing questions about Java errors and exceptions in the Java puzzles by Joshua Bloach and Neil Gafter.

I also often see interview questions about Java errors and exceptions in newcomers and experienced Java interviewers. Of course, there are many questions about exceptions that I haven't touched on. If you have some good questions, please tell me, I will try my best to include these questions in this java exception question and answer series. There is one last question I leave for my partners, "Why are Java exceptions considered better than returning error codes?" Tell me what you think about the Java Exception Interview Q & A series here.

Original: http://www.oschina.net/translate/10-java-exception-and-error-interview-questions-answers-programming

Java Exception and Error Interview Questions 10 Questions 10 Answers

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: info-contact@alibabacloud.com 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.