Java Exception

Exception Basics

  • Throwable
    • Error
    • Exception
      • RuntimeException
      • IOException

这里写图片描述

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(n<len) {
    throw 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值