Java Exception

Exception Basics

  • Throwable
    • Error
    • Exception
      • RuntimeException
      • IOException

Java Exception_第1张图片

Unchecked Exception = Error + RuntimeException
Checked Exception = RuntimeException

Compiler requires you to provide handlers for all checked exceptions.

RuntimeException is programmer’s fault, which means this can be avoided by proper testing in the program

NOTE: override methods in subclass CANNOT throw more general exceptions than superclass methods. But it is OK to throw more specific exceptions. If superclass methods do not throw checked exceptions, subclass methods CANNOT throw any.

If a method declares to throw an exception, it may throw an exception of that class or of any of its subclasses.

Return value in finally block will mask the return value in try block. This may not what you want, be cautious.

To declare a method can throw an exception

public Image loadImage(String s) throws FileNotFoundException, EOFException

To throw an exception

if(nthrow new EOFException();
}

Below style is strongly recommended
* Code is more readable, inner try/finally block has single responsibility, outer try/catch block also has single responsibility
* If having exceptions in finally block, e.g., fail to close resource, they can be handled properly in the outer catch block

try {
    try {
        // code that may throw exceptions
    }
    finally {
        // close resource here
    }
}
catch (IOException e) {
    // handle exceptions
}

Create your own exception

class FileFormatException extends IOException {
    public FileFormatException() {
    }

    public FileFormatException(String message) {
        super(message);
    }
}

As of Java SE7, you can catch multiple exception types in the same catch clause
* Catching exception types are not subclasses of one another
* Make your code look simpler and more efficient

try {
    // code might throw exceptions
}
catch (FileNotFoundException | UnkonwnHostException e) {
    // handler
}
catch(IOException e) {
    // handler
}

Rethrowing and Chaining Exceptions

try {
    // code that might cause SQLException
}
catch (SQLException e) {
    Throwable se = new ServletException("database error");
    se.initCause(e);
    throw se;
}

Later you can

Throwable e = se.getCause();

As of Java SE 7, you can use try-with-resource statement
* If resource implement AutoCloseable interface (or Closable interface which is a sub interface of Autoacloseable). This interface has a single close method
* If both try block and close throw exceptions, the original exception is rethrown, and others thrown by close are caught and added to the original exception with addSuppresed() method, you can later get them by calling getSuppresed() method

try (Scanner in = new Scanner(new FileInputStream("/usr/share/dict/words")), 
    PrintWriter out = new PrintWriter("out.txt")) {
    // Your code that might throw exceptions
}

Tipas for Using Exceptions

  1. Exception handling is not supposed to replace a simple test
    • A simple test is far more efficient than exception handling
  2. Do not micromanage exceptions
    • Wrap the entire task in a try block, separate normal processing from error handling
  3. Make good use of the exception hierarchy
    • Turn an exception into another exception that is more appropriate. Do not throw a general exception, such as RuntimeException; Do not catch a general exception, such as Throwable. Make your code easy to read and maintain.
  4. Do not squelch exceptions
  5. When you detect an error, “tough love” works better than indulgence
  6. Propagating exceptions is not a sign of shame
    • Propagate the exception to high level methods when appropriate, it often better knows how to handle this exception
  7. Throw early, catch late

你可能感兴趣的:(java,java)