Java exception--catch exception + throw exception and exception chain again

Source: Internet
Author: User
Tags getmessage stack trace throw exception java se

"0" README

0.1) This article describes + source code is transferred from core Java Volume 1, to understand Java exception-catch exception + throw exception and exception chain of knowledge;

"1" catches exception related

1.1) If an exception occurs without any further capture, the program will run to terminate: and print out the exception information on the console, including the contents of the exception type stack;
1.2) to catch an exception, you must set the Try/catch statement block:

    • 1.2.1) If you throw a class of exceptions declared in a catch clause in a try statement block,
      • case1) The program skips the rest of the code in the try statement block;
      • case2) program executes the processor code in the CATCH clause;
    • 1.2.2) If no exception is thrown in the try statement block, the program skips the catch clause;
    • 1.2.3) If any code in the method throws a type of exception that is not declared in the catch clause, the method exits immediately;

1.3) Look at a litchi: (see a program code that reads text to demonstrate the process of catching exceptions)

publicvoidread(String filename){    try    {        new FileInputStream(filename);  // 创建输入流        int b;        while((b=in.read()) != -1)            process input    }    catch(IOException exception)    {        // 打印栈轨迹;    }}

Analysis of the above code:

    • A1) It is important to note that most of the code in a try statement is easy to understand, reading and processing lines of text until a file terminator is encountered (the Read method may throw a IOException exception)
    • A2) In this case, you will jump out of the entire while loop, enter the catch clause, and generate a stack trace;

1.4) is there any other way to handle the above exception handling method for an ordinary program?

    • 1.4.1) in general, the best choice is to do nothing but pass the exception to the caller, and if the Read method has an error, let the caller of the Read method handle it.
    • 1.4.2) If this is the case, you must declare that the method may throw a ioexception (passing the exception to the caller);
publicvoidreadthrows IOException{        new FileInputStream(filename);  // 创建输入流        int b;        while((b=in.read()) != -1)            process input}

Attention) compiler strictly executes the throws specifier. if a method that throws a checked exception is called, it must be processed, or it will continue to be passed;
1.5) which method is better for the above two methods of handling exceptions? (method1: To add a try/catch statement block to a function that could have an exception); METHOD2: Passing an exception (throw) to the caller, the caller handles it)

    • 1.5.1) in general, you should capture exceptions that know how to handle and continue passing exceptions that do not know what to do, and if you want to pass an exception, you must add a throws specifier at the header of the method to inform the caller that this method might throw an exception;
    • 1.5.2) read the API to see what kind of exception the method might throw, and then decide whether to handle it yourself or add it to the throws list;

Attention) There is an exception to the above rule: as mentioned earlier, if you write a method that overrides a superclass, and this method does not throw an exception, then this method must capture every checked exception that appears in the method code. The exception class scope listed by the superclass method is not allowed in the throws specifier of the subclass, (thatis, the parent class method does not throw an exception, your subclass method is not allowed to throw an exception, you can only add the Try/catch statement block yourself)

"2" captures multiple exceptions

2.1) Multiple exceptions can be caught in a try statement block, and different types of exceptions are handled differently. You can use a separate catch clause for each exception type in the following ways;

try{}catch(FileNotFoundException e){}catch(UnknownHostException e){}catch(IOException e){}

2.2) To get more information about the exception object: You can try using e.getmessage () to get detailed error information, or use E.getclass (). GetName (); Get the actual type of the exception object;
2.3) Merge catch clauses: in Java SE7, multiple exception types can be captured in the same catch clause. For example, if you have the same actions for missing files and unknown host exceptions, you can merge catch clauses:

try{}catch(FileNotFoundException | UnknownHostException e){}catch(IOException e){}

Attention)

    • A1) This feature is required only if the type of exception being caught does not have a subclass relationship with each other;
    • A2) When capturing multiple exceptions, the exception variable is implied as a final variable. For example, you cannot assign a different value to E in the following clause body;
      catch (FileNotFoundException | | Unknownhostexception e) {}
    • A3) capturing multiple exceptions will not only make your code look simple but also be more efficient. The resulting bytecode contains only a block of code corresponding to a public catch clause;
"3" throws the exception and the exception chain again

3.1) An exception can be thrown in the catch clause, which is intended to change the exception type;

    • 3.1.1) Look at a litchi:
try{}catch(SQLException e){    thrownew ServletException("data error : " + e.getMessage());}

Analysis of the above code:

    • A1) here, Servletexception is constructed with a constructor with the text of the exception message;
    • A2) However, there can be a better way, and the original exception is set to the cause of the new exception:
try{}catch(SQLException e){    new ServletException("database error");    se.initCause(e);    throw se;}
    • A3) When this exception is caught, you can use the following statement to get back the original exception:
Throwable e = se.getCause();

Attention) strongly recommends the use of this packaging technique, which allows the user to throw advanced exceptions in the subsystem without losing the small details of the original exception; (recommended to use strongly recommended)

Hint)

    • H1) Packaging technology is useful if a checked exception occurs in a method and is not allowed to be thrown. We can also catch this checked exception and wrap it into a runtime exception;
    • H2) Sometimes you just want to record an exception and then re-throw it without making any changes:
try{    access the database}catch(Exception e){    logger.log(level, message, e);    throw e;}
    • H3) Before the Java SE7, put the above code into the following method, there will be a problem;
publicvoidupdateRecordthrows SQLException
    • Because the Java compiler looks at the throw statement in the catch block and then looks at the type of E, it indicates that this method can throw any exception and not just SQLException;
    • H4) after Java SE 7 (compiler detection syntax is legal): The compiler traces the e from the try block, assuming that the only checked exception in this try block is the SqlException instance, and that if E is not changed in the catch block, the perimeter method is declared as Throws SQLException is legal;

Java exception--catch exception + throw exception and exception chain again

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.