1.throw操作员

当一个异常被一个catch块捕获时,直到它被抛给 Java 机器,它只是一个继承Exception(或者更确切地说,Throwable)的对象。异常对象本身没有任何神奇的属性。

异常如何工作的所有逻辑只是 Java 机器在抛出异常时的一种特殊行为方式。

您始终可以将捕获的异常重新抛出给 Java 机器。为此,您需要使用throw运算符:

throw exception;

例子:

代码 控制台输出
try
{
   int d = 2/0;
}
catch(Exception except)
{
   System.out.println("Caught the exception");
   throw except;
}
Caught the exception

在这段代码中,我们捕获了一个异常,在屏幕上显示了一条关于它的消息,然后重新抛出它。

catch重新抛出的异常不能被同一块中的其他块捕获try


2. 你的例外

顺便说一句,你可以自己创建一个异常对象:它只是一个对象,其类型是Exception或继承它的类。并扔掉它。

这比听起来容易。例子:

代码 控制台输出
try
{
   throw new RuntimeException();
}
catch(Exception except)
{
   System.out.println("Caught the exception");
   throw except;
}
Caught the exception

在上面的示例中,我们创建了一个新的异常对象,其类型为RuntimeException并立即使用运算符将​​其抛出throw

它会立即被catch块捕获,因为 RuntimeException 继承了Exception. 该catch (Exception except)代码捕获所有继承该类的类的异常对象Exception



3.finally关键词

另一个重点。有时程序员需要执行一些操作,而不管代码中是否发生异常。例如,假设我们打开一个文件进行写入。打开的文件必须通过调用关闭close()

try
{
   // Code where an exception might occur
}
catch(ExceptionType name)
{
   // Exception handling code
}
finally
{
   // Code that must executed no matter what happens
}

为了执行这些强制性操作,另一种块 ( finally) 被添加到try-catch构造中,从而创建了try-catch-finally构造。它看起来像这样:

例子:

FileInputStream source = null;
try
{
   source = new FileInputStream("c:\\note.txt");
   source.read();
}
catch(Exception except)
{
   System.out.println("Caught the exception");
   throw except;
}
finally
{
   if (source != null)
      source.close();
}

finally块中的代码 将在任何情况下执行,无论是否有异常。即使抛出异常但未被捕获,该finally块仍会执行。

顺便说一句,如果您不想捕获异常,但确实需要一个finally块,请使用结构的简写符号try-catch-finally:一个try-finally块。它看起来像这样:

try
{
   // Code where an exception might occur
}
finally
{
   // Code that must executed no matter what happens
}