它告诉类的客户端 DoBlah 方法可以抛出 BlahException 或任何其他扩展它的异常.
如果是受检查的异常,编译器将要求将对此方法的调用包装在 try/catch 块中。如果未选中,他们可以选择不捕获异常,但他们必须意识到,如果不这样做,它将在调用堆栈中进一步向上冒泡。
它没有说明任何有关 NullPointException 或错误等未经检查的异常的信息。这些也可以随时抛出。 throws 子句中不需要它们。
此代码显示了它的工作原理:
异常演示.java:
package exceptions;
public class ExceptionDemo
{
public static void main(String[] args)
{
ExceptionDemo demo = new ExceptionDemo();
try
{
// Removing the try/catch will result in a compilation error
demo.doChecked();
}
catch (CheckedException e)
{
e.printStackTrace();
}
// Note: Not inside a try/catch, in spite of the throws clause
demo.doUnchecked();
}
public void doChecked() throws CheckedException
{
System.out.println("doing something that may throw a checked exception");
}
// Note: "throws" clause is unnecessary for an unchecked exception
public void doUnchecked() throws UncheckedException
{
System.out.println("doing something that may throw an unchecked exception");
}
}
检查异常.java:
package exceptions;
public class CheckedException extends Exception
{
public CheckedException()
{
super();
}
public CheckedException(String message)
{
super(message);
}
public CheckedException(String message, Throwable cause)
{
super(message, cause);
}
public CheckedException(Throwable cause)
{
super(cause);
}
}
UncheckedException.java:
package exceptions;
public class UncheckedException extends RuntimeException
{
public UncheckedException()
{
super();
}
public UncheckedException(String message)
{
super(message);
}
public UncheckedException(String message, Throwable cause)
{
super(message, cause);
}
public UncheckedException(Throwable cause)
{
super(cause);
}
}