11th. Exceptions, logs, assertions and debugs

Source: Internet
Author: User

11th Chapter Exception, log, assert, Debug

Users may not be able to use this program because of the loss of user data due to program errors or the impact of some external environments. To avoid this, the following points should be achieved:

    • Advertise Errors to users

    • Save All Operation results

    • Allows the user to exit the program in the appropriate form.

11.1 Handling Exceptions

When some operations are not completed due to an error, the program should:

    • Returns to a security state and enables the user to execute some other command;

    • Allows the user to save the results of all operations and terminate the program in an appropriate manner

The task of exception handling is to transfer control from the place where the error occurred to the processor that can handle the error. Errors and issues that may occur in the program:

    1. User input Error

    2. Device error

    3. Physical limit (disk full)

    4. A code error, for example (the method returns an error answer, or an incorrect call to another method; An invalid array subscript was used; an attempt was made to find a data item that does not exist in the hash table; An attempt to retract an empty stack. )

11.1.1 Anomaly Classification

Exception objects are derived from an instance of the Throwable class, and users can create their own exception classes if the Java built-in exception class does not meet the requirements.

The error class hierarchy describes internal errors and resource exhaustion errors for the Java Runtime system.

In Java design, you need to focus on the exception hierarchy. Two branches:

    • Derived from RuntimeException (program error caused)

      • Wrong type conversions

      • Array access is out of bounds (avoid arrayindexoutofboundsexception by checking array subscripts)

      • Access a null pointer (check if it is empty before using the variable to prevent nullpointerexception)

    • Contains other exceptions (the program itself is not a problem, such as an I/O error causes an exception)

      • Attempting to read data after the end of the file

      • An attempt was made to open a malformed URL

      • An attempt was made to look up a class object based on a given string, and the string represented by it does not exist

If there is a runtimeexception exception, it must be your problem.

Classification of exceptions:

    • No exception checked

      • Derived from error

      • Derived from RuntimeException

    • Other exceptions are known as checked exceptions.

11.1.2 declaration has checked for exceptions

A method not only needs to tell the compiler what value to return, but also tells the compiler what error it is likely to occur. The method should not declare any exceptions that may be excluded in its collection. This can be used to reflect from the header which class of checked exceptions the method might throw.

You write your own method by not having to declare the exceptions that might be thrown. There are four things to remember that should throw an exception:

    • Call a method that throws a checked exception, such as FileInputStream

    • An error was found while the program was running and a throw statement was used to throw a checked exception

    • A program error, such as a[-1] = 0 throws a arrayindexoutofboundsexception

    • Internal exceptions for Java virtual machines and run-time libraries

If the first two cases occur, you must tell the programmer who called this method to throw an exception. Because any method that throws an exception can be a death trap, if no processor catches the exception, the currently executing thread ends.

For Java methods that might be used by others, you should declare the exception that the method might throw in the method header according to the exception specification.

Class myanimation{... public iamge loadimage (String s) throws IOException {...}}

Throws multiple checked exceptions and must list all exception classes at the header, separated by commas

Class myanimation{... public iamge loadimage (String s) throws Eofexceoption,malformedurlexception {... }}

There is no need to declare a Java internal error, which is an error derived by error. You should also not declare those that derive from RuntimeException without checking for exceptions. These errors should be spent more time correcting errors in the program than explaining the likelihood of these errors occurring.

In summary, a method must declare all the checked exceptions that may be thrown, without checking that the exception is either uncontrollable (Error) or should be avoided (runtimeexception).

In addition to declaring exceptions, you can also catch exceptions. This causes the exception to be left out of the way and does not require the throws specification.

Warning: if a method of a superclass is overridden in a subclass, the child class declares that the checked exception cannot exceed the exception range of what is in the superclass method. If the superclass method does not throw any checked exceptions, the subclass should not throw any checked exceptions.

11.1.3 How to throw an exception

For an already existing exception class:

    1. Find a suitable exception class

    2. Create an object of this class

    3. Throws an Object

Once the method throws an exception, this method cannot be returned to the caller.

For example, read a file header, read the end of a character, think it is not normal, want to throw an exception.

The first thing to decide what type of exception to throw boils down to IOException is a good choice, and a closer look at the Java API will reveal that the eofexception is encountering an unexpected EOF signal during the input process.

String ReadData (Scanner in) throws eofexception{... while (...)        {if (!in.hasnext ())//eofexception {if (N<len) throws new Eofexception;       }        ...    } return s;}

The Eofexception class also has a constructor for a string argument.

String gripe = "Content-length:" +len+ ". Received: "+n;throws new Eofexception (gripe);
11.1.4 Creating exception classes

Defines a class that derives from the exception class, or its subclasses. It is customary to define such a class to contain two constructors, one default, and the other a constructor with a message describing it (the ToString method of the superclass Throwable will print these details, which is useful in debugging).

Class Filefromatexception extends ioexception{public fileformatexception () {} public fileformatexception (String grip    e) {super (gripe); }}
11.2 Catching exceptions

Catch exception with Try/catch statement block.

try{code more Code}catch (Exceptiontype e) {handler for this type}

If any code in the try statement block throws an exception class that is described in the catch clause, then:

    1. The program skips the rest of the code in the TRY statement block

    2. The program executes the processing code in the catch clause

If no exception is thrown in the try, the program skips the catch clause. If you throw an exception type that is not declared in the catch clause, the method exits immediately.

If you call a method that has checked for an exception, you must either process it or pass it out. You should usually capture the ones that know how to handle and pass out exceptions that don't know how to handle them (throws). One exception: If you write a method that overrides a superclass, and if this method throws an exception, then this method must capture every checked exception that appears in the method code.

11.2.1 Capturing multiple exceptions
try{code, might throws Exceptions}catch (Malformedurlexception E1) {Emergency Action for malformed Urls}catch (Un Kownhostexception E2) {Emergency Action for unknown Hosts}catch (IOException e3) {Emergency action for all other I/O Problems}

The exception object (E1,E2,E3) may contain information about the exception itself. To get more information available

E1.getmessage ()

Or get the type of the exception object

E3.getclass (). GetName ()
11.2.2 again throws exception and exception chain

An exception can be thrown in a catch clause so that the purpose of the child is to change the type of the exception. servletexception example. The code executing the servlet might not want to know the details of the error, but would like to know for sure if the servlet is faulty.

try{access the Database}catch (SQLException e) {throw new Servletexception ("Database error:" +e.getmessage ());}

In Java SE 1.4, there is a better way to handle

try{access the Database}catch (SQLException e) {throwable se = new servletexception ("Database error:"); Se.initcause (e);//Get back the original exception throw SE;}

This packaging technique is strongly recommended to allow users to throw advanced exceptions in the subsystem without losing the original exception details. If a class is checked for exceptions in a method and is not allowed to be thrown, the packaging technique is useful. Captures this checked exception and wraps it as a run-time exception.

11.2.3 finally clause

If the method obtains some local resources, and only this method knows itself, and if these resources must be recycled before exiting the method, then there will be a resource recycling problem. The finally clause solves this problem. If you use Java to write a database program, you need to use this technique to close the connection to the database. The finally clause is executed regardless of whether the exception is captured.

Graphics g = Image.getgraphics (); try{//1 code that might throw exception//2}catch (IOException e) {//3 sh OW error dialog//4}finally{//5 g.dispose ();}

The finally clause is executed regardless of how it occurs. Using the return statement in the finally clause overwrites the previous return statement.








11th exception, log, assert, and debug

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.