catalogue

  • 10.0.0.1 What runtime exceptions have you seen? What does the exception handling mechanism know? How to classify exceptions in terms of whether they need to be handled?
  • 10.0.0.2 Using Java Exception handling? How does exception handling work? What is the difference between checked and unchecked exceptions in Java?
  • 10.0.0.3 What good practices do you follow when handling exceptions? What is the difference between the throw and throws keywords in Java?
  • Do you know what an “exception chain” is? What exceptions have been implemented and how to write them? Can I have an empty catch block?
  • 10.0.0.5 What are the important methods of Java exception classes? What are the different scenarios that lead to “exceptions in the main thread”?
  • 10.0.0.6 What is wrong with subclass code inheriting from parent class? For IOException or Exception, can you write casually?
  • 10.0.0.7 Why do I pay attention to the exception hierarchy in a catch? What problems should be paid attention to?

Good news

  • Summary of blog notes [October 2015 to present], including Java basic and in-depth knowledge points, Android technology blog, Python learning notes, etc., including the summary of bugs encountered in daily development, of course, I also collected a lot of interview questions in my spare time, updated, maintained and corrected for a long time, and continued to improve… Open source files are in Markdown format! Also open source life blog, since 2012, accumulated a total of 500 articles [nearly 1 million words], will be published on the Internet, reprint please indicate the source, thank you!
  • Link address:Github.com/yangchong21…
  • If you feel good, you can star, thank you! Of course, also welcome to put forward suggestions, everything starts from small, quantitative change causes qualitative change! All blogs will be open source to GitHub!

10.0.0.1 What runtime exceptions have you seen? What does the exception handling mechanism know? How to classify exceptions in terms of whether they need to be handled?

  • Runtime exceptions: The Throwable inheritance hierarchy can be divided into two categories: Error and Exception:
    • Error: An exception that cannot be recovered by the program, indicating a serious problem in running the application; Occurs when the VM itself or when the VM attempts to execute an application, such as Virtual MachineError (Java VM running error) or NoClassDefFoundError (class definition error). It is an untraceable exception, that is, it does not force the programmer to handle it, and even if it does not handle it, syntax errors will not occur.
    • Exception: An Exception that can be recovered by the program itself. There are two main categories:
      • RuntimeException: An exception caused by a problem in the program itself; Such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript bounds); Belongs to an untraceable exception.
      • Non-runtime exceptions: Exceptions caused by problems outside the program; Exceptions other than RuntimeException, such as FileNotFoundException (file does not have an exception); Is a traceable exception that forces the programmer to handle it, or a syntax error occurs if it is not handled.
  • Exception handling mechanism
    • Catch an exception: An exception is automatically thrown by the system, that is, try catching an exception ->catch handling an exception ->finally handling the exception
    • Throw exception: An exception object is explicitly thrown in a method, after which the exception is thrown up the call hierarchy to be handled by the calling method. Throws throws and declares exceptions
    • Custom exception: Inherits the Execption class or its subclasses
    • Tech blog summary
  • How to classify exceptions in terms of whether they need to be handled
    • Anomalies can be divided into two types: unexamined anomalies and inspected anomalies:
      • Unchecked exceptions: All exceptions derived from Error or RuntimeException;
      • Checked exceptions: Remove all exceptions that are not checked.

10.0.0.2 Using Java Exception handling? How does exception handling work? What is the difference between checked and unchecked exceptions in Java?

  • Using Java exception handling?
    • 1. Try… Catch statement
    • 2.finally statement: Code that must be executed in most cases
    • Throws clause: declares a possible exception class
    • Throw: Throws a concrete exception object.
  • How does exception handling work?
    • The Java Virtual machine uses the Method Invocation stack to track a series of method calls in each thread. If an exception is thrown during the execution of a method, the Java virtual machine must find a catch block that can catch the exception. When the Java virtual machine traces back to the method at the bottom of the call stack and still does not find a block of code to handle the exception, it does so step by step, first printing the exception for the method call stack, and then terminating the thread if it is not the main thread.
  • The difference between checked and unchecked exceptions in Java
    • Check exception (CheckedException)
      • All exceptions in Java that are not derived from RuntimeException are checked exceptions. If a function has an operation that throws a check exception, its function declaration must contain a throws statement. The function calling the modified function must also handle the exception. If it does not handle the exception, it must declare a throws statement on the calling function.
      • Checking exceptions are a JAVA initiative that imposes requirements on exception handling at compile time. A large number of exceptions in JDK code are check exceptions, including IOExceptions, SQLException, and so on.
    • UncheckedException (UncheckedException)Tech blog summary
      • All derived classes of RuntimeException in Java are non-checking exceptions. In contrast to checking exceptions, non-checking exceptions do not add throws statement in function declaration and do not require mandatory processing on function calls.
      • Common NullPointException, ClassCastException is common non-checking exception. Non-checking exceptions can be done without a try… Catch is handled, but if an exception is raised, the exception is handled by the JVM. It is best to use exception handling mechanisms for RuntimeException subclasses as well. Although RuntimeException exceptions can be made without a try… If an exception occurs, the execution of the program will be interrupted. Therefore, in order to ensure that the program can still be executed after another error, it is best to use try when developing code. Catch’s exception handling mechanism.

10.0.0.3 What good practices do you follow when handling exceptions? What is the difference between the throw and throws keywords in Java?

  • What good practices do you follow when handling exceptions?
    • Exception handling is critical in project design, so mastery of exception handling is essential. There are many best practices for exception handling, and here are a few that improve the robustness and flexibility of your code:
      1. Instead of returning null, a NullPointerException is returned when a method is called. Because null Pointers are the most disgusting of Java exceptions.
      1. Don’t write code in a catch block. An empty catch block is an error event in exception handling because it simply catches the exception without any handling or prompting. Usually you should at least print out the exception message, but it is best to handle the exception message as required.
    • 3) If you can throw checked exceptions, try not to throw unchecked exceptions. You can improve the readability of your code by removing duplicate exception handling code.
      1. Never let your database-related exceptions show up on the client. Since the vast majority of database and SQLException exceptions are managed exceptions, in Java, you should handle the exception information at the DAO layer and then return the handled exception information that the user can understand and correct according to the exception prompt.
      1. In Java, be sure to call the close() method ina finally block after a database connection, database query, and stream processing.
  • What is the difference between the throw and throws keywords in Java?
    • Tech blog summary
    • Throws throws. You can also declare unchecked exceptions, but this is not mandatory by the compiler. If a method throws an exception it needs to be handled when the method is called.
    • A throw is used to throw any exception. Syntactically you can throw any Throwable (Throwable or any Throwable derived class). A throw interrupts a program and is therefore used instead of a return.
    private static voidshow() {throw new UnsupportedOperationException (" exceptions "); }Copy the code

Do you know what an “exception chain” is? What exceptions have been implemented and how to write them? Can I have an empty catch block?

  • Do you know what an “exception chain” is?
    • “Exception chain” is a very popular exception handling concept in Java. It refers to an exception chain that is created when one exception is thrown while another exception is being handled. This technique is mostly used to encapsulate “checked exceptions” as “unchecked exceptions” or runtimeexceptions. 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 root of the exception through the getCause() and initCause() methods.
  • What exceptions have been implemented by custom?
  • Can I have an empty catch block?
    • You can have an empty catch block, but this is the worst example of programming. There should be no empty catch block, because if an exception is caught by that block, we will have no information about the exception and it will be a nightmare to debug it. There should be at least one logging statement to record exception details in the console or log file.
    • Tech blog summary

10.0.0.5 What are the important methods of Java exception classes? What are the different scenarios that lead to “exceptions in the main thread”?

  • What are the important methods of Java exception classes?
    • Exception and all of its subclasses do not provide any special methods to use; all of their methods come from their base class, Throwable.
      • String getMessage(): The method returns String information about the Throwable, which is available when an exception is created through the constructor.
      • String getLocalizedMessage() : This method is overridden to get an exception message in the local language returned to the caller. Throwable classes typically just use the getMessage() method to return exception information.
      • Synchronized Throwable getCause(): This method returns the cause of the exception or null if the cause is not known. (if not id)
      • String toString(): The Throwable method returns Throwable information in String format, including the Throwable name and localization information.
      • Void printStackTrace() : This method prints stack trace information to the standard error stream. This method can be overloaded by taking PrintStream and PrintWriter as arguments so that the stack trace can be printed to a file or stream.
  • What are the different scenarios that lead to “exceptions in the main thread”?
    • Some common main thread exceptions are:
      • Anomaly in the main Java thread. Lang. UnsupportedClassVersionError: when your Java classes from another version of the JDK compiler and you attempt to run a Java version from another when it will be this exception.
      • In the main Java thread. Lang. NoClassDefFoundError exception: this exception has two variants. The first is where you provide the full name of the class with the.class extension. The second case is that no class is found.
      • Anomaly in the main Java thread. Lang. NoSuchMethodError: main: when you try to run a class, there is no main method will be the exception.
      • Tech blog summary
      • A thread in the “main” Java. Lang. ArithmeticException: whenever any exception thrown from the main method, it will print out the anomaly is the console. The first part explains how the exception is thrown from the main method, the second part prints the name of the exception class, and then the exception message after the colon.

10.0.0.6 What is wrong with subclass code inheriting from parent class? For IOException or Exception, can you write casually?

  • What’s wrong with this 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"); }}Copy the code
    • This code will generate an error for subclasses overwriting the start method. Because the override of every method in Java is regular, an override method cannot throw an exception with a higher inheritance than the original method. Since the start method here throws IOException in the superclass, all start methods in subclasses can only throw either IOExcepition or its subclass, but not its superclass, such as Exception.
  • For IOException or Exception, can you write casually?
    • Be sure not to write casually, easy to cause confusion. Let’s take a look at the code for a simple example! Tech blog summary
    public static void start(){
       System.out.println("Java Exception"); } public static void main(String args[]) { try{ start(); }catch(IOException e){ e.printStackTrace(); }}Copy the code
    • In the Java exception example above, the compiler will report an error when handling IOException. IOException is checked, and the start method does not throw IOException. Java.io.IOException is not thrown in the body of a try statement, “but if you change IOException to Exception, the compiler’s error will disappear, because Exception can be used to catch all runtime exceptions, so there is no need to declare a throw statement. I like this deceptive Java Exception interview question because it doesn’t make it easy to find IOException or Exception. You can also find some confusing questions about Java errors and exceptions in JoshuaBloach and NeilGafter’s Java puzzles.

10.0.0.7 Why do I pay attention to the exception hierarchy in a catch? What problems should be paid attention to?

  • When catching an exception, why pay attention to the exception hierarchy in a catch? What problems should be paid attention to?
    • Notice, you have to pay attention to the hierarchy in catch. Here is a simple case, you can understand why pay attention to hierarchy!
    • Tech blog summary
    public static void start() throws IOException, RuntimeException{
        throw new RuntimeException("Not able to Start"); } public static void main(String args[]) { try { start(); } catch (Exception e) { e.printStackTrace(); } catch (RuntimeException e2) { e2.printStackTrace(); }}Copy the code
    • This code throws a compilation exception error in the RuntimeException type variable “e2” that captures the exception block. Because Exception is a superclass of RuntimeException, all Runtimeexceptions in the start method are caught by the first catch Exception block, so the second catch block cannot be reached, “The exception that is thrown Java. Lang. RuntimeException has already had caught” compilation errors.

The other is introduced

01. About blog summary links

  • 1. Tech blog round-up
  • 2. Open source project summary
  • 3. Life Blog Summary
  • 4. Himalayan audio summary
  • 5. Other summaries

02. About my blog

  • My personal website: www.yczbj.org, www.ycbjie.cn
  • Github:github.com/yangchong21…
  • Zhihu: www.zhihu.com/people/yang…
  • Jane: www.jianshu.com/u/b7b2c6ed9…
  • csdn:my.csdn.net/m0_37700275
  • The Himalayan listening: www.ximalaya.com/zhubo/71989…
  • Source: China my.oschina.net/zbj1618/blo…
  • Soak in the days of online: www.jcodecraeer.com/member/cont.
  • Email address: [email protected]
  • Blog: ali cloud yq.aliyun.com/users/artic… 239.headeruserinfo.3.dT4bcV
  • Segmentfault headline: segmentfault.com/u/xiangjian…
  • The Denver nuggets: juejin. Cn/user / 197877…