
“我今天要讲解一个点。在 Java 中,异常分为两种:已检查和未检查(即必须捕获的异常和不必捕获的异常)。默认情况下,必须捕获所有异常。”
“你能在自己的代码中故意抛出异常吗?”
“你可以在自己的代码中抛出任何异常。你可以编写自己的异常。我们稍后讨论这一点。现在我们着重讲讲 Java 机器抛出的异常。”
“好的。”
“如果方法中抛出(发生)ClassNotFoundException 或 FileNotFoundException,那么程序员仅需在方法声明中指出它们。这些就是已检查异常。通常看似来如下所示:”
已检查异常示例 |
---|
|
|
|
“所以我们只在‘throws’后面写逗号分隔的异常列表,对吗?”
“对。但实际上不止这些。要使程序编译,下例中调用 method1
的方法必须执行一个操作:要么捕获异常,要么重新抛出异常(给调用者),在自己的声明中指出重新抛出的异常。”
“再说一次。如果你的 main 方法要调用声明中包含‘throws FileNotFoundException, …’的方法,则需要执行一个操作:
1) 捕获 FileNotFoundException, …
你必须在 try-catch 块中封装调用不安全方法的代码。
2) 不捕获 FileNotFoundException, …
你必须在 main 方法的抛出异常列表中添加这些异常。”
“能否举个例子?”
“请看以下示例:”
public static void main(String[] args)
{
method1();
}
public static void method1() throws FileNotFoundException, ClassNotFoundException
{
//如果文件不存在,则抛出 FileNotFoundException
FileInputStream fis = new FileInputStream("C2:\badFileName.txt");
}
“这个例子中的代码将无法编译,因为 main 方法调用 method1(),这抛出了必须捕获的异常。”
“要使其编译,我们要在 main 方法中添加异常处理。有两种方法:”
public static void main(String[] args) throws FileNotFoundException, ClassNotFoundException
{
method1();
}
public static void method1() throws FileNotFoundException, ClassNotFoundException
{
//如果文件不存在,则抛出 FileNotFoundException
FileInputStream fis = new FileInputStream("C2:\badFileName.txt");
}
“在这里,我们用 try-catch 捕获:”
public static void main(String[] args)
{
try
{
method1();
}
catch(Exception e)
{
}
}
public static void method1() throws FileNotFoundException, ClassNotFoundException
{
//如果文件不存在,则抛出 FileNotFoundException
FileInputStream fis = new FileInputStream("C2:\badFileName.txt");
}
“越发明显。”
“请看下面的例子。它会帮助你了解剩下的内容。”
public static void method2() throws FileNotFoundException, ClassNotFoundException
{
method1();
}
public static void method3() throws ClassNotFoundException
{
try
{
method1();
}
catch (FileNotFoundException e)
{
System.out.println("FileNotFoundException 已被捕获。");
}
}
public static void method4()
{
try
{
method1();
}
catch (FileNotFoundException e)
{
System.out.println("FileNotFoundException 已被捕获。");
}
catch (ClassNotFoundException e)
{
System.out.println("ClassNotFoundException 已被捕获。");
}
}
“还有一类异常是 RuntimeException 和继承它的类。你无需捕获它们。这些是未检查的异常。它们通常难以预测。你大可以其人之道还治其人之身,不过不必在 throws 子句中指出。”
GO TO FULL VERSION