异常类型 - 1

“我今天要讲解一个点。在 Java 中,异常分为两种:已检查未检查(即必须捕获的异常和不必捕获的异常)。默认情况下,必须捕获所有异常。”

“你能在自己的代码中故意抛出异常吗?”

“你可以在自己的代码中抛出任何异常。你可以编写自己的异常。我们稍后讨论这一点。现在我们着重讲讲 Java 机器抛出的异常。”

“好的。”

“如果方法中抛出(发生)ClassNotFoundExceptionFileNotFoundException,那么程序员仅需在方法声明中指出它们。这些就是已检查异常。通常看似来如下所示:”

已检查异常示例
public static void method1() throws ClassNotFoundException, FileNotFoundException
public static void main() throws IOException
public static void main() // 不抛出任何异常

“所以我们只在‘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 方法中添加异常处理。有两种方法:”

选项 1:我们只要重新抛出异常(给调用者):
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 捕获:”

选项 2:捕获异常:
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 已被捕获。");
    }
}
3
任务
Java 语法,  第 9 级课程 4
已锁定
输入代码
有时你不需要思考,只需要敲击键盘把它打出来!尽管看似矛盾,但有时候你的手指会比你的意识有更好的“记忆力”。这就是为什么在秘密 CodeGym 中心进行培训时,有时会要求你完成一些输入代码的作业。通过输入代码,你将习惯这些语法,并获得一些暗物质。更重要的是,你会与懒惰作斗争!

“还有一类异常是 RuntimeException 和继承它的类你无需捕获它们。这些是未检查的异常。它们通常难以预测。你大可以其人之道还治其人之身,不过不必在 throws 子句中指出。”