楼主同志,呵呵,一般java学习的书都会有一章的篇幅去介绍java的异常捕捉处理机制,而且我相信你对于在方法上去throws 和 try catch有什么不同也不太理解,
去sun的Exception lesson 看看吧:http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
这几句说明也不错:
Java divides exceptions into two categories:
- General exceptions
- Run-time exceptions
The general exceptions must be handled. That is, a try-catch must either be nested around the call to the method that throws the exception or the method must explicitly indicate with throws that it can generate this exception. (Then other methods that invoke this method must then catch the exception or throw it up the line.) The compiler will throw an error message if it detects an uncaught exception and will not compile the file.
The run-time exceptions do not have to be caught. This avoids requiring that a try-catch be place around, for example, every integer division operation to catch a divide by zero or around every array variable to watch for indices going out of bounds.
However, you should handle possible run-time exceptions if you think there is a reasonable chance of one occurring. In the above string parsing example, the NumberFormatException extends (we discuss subclassing in Chapter 4) RuntimeException so it is optional to catch this error.
You can use multiple catch clauses to catch the different kinds of exceptions that code can throw as shown in this snippet:
try
{
... some code...
} catch ( NumberFormatException e)
{
...
} catch (IOException e)
{
...
} catch (Exception e)
{
...
} finally // optional
{
...this code always executed even if
no exceptions...
} |
Here there are two catch statements for Exception subclasses (subclassing will be discussing in Chapter 4),and one for any other Exception instance. Regardless of whether the code generates an exception or not, the finally code block will always execute.
Exception handling is thus based on try-catch operation, the throws and throw keywords, and the Exception class and its subclasses.