它告诉您的类的客户端,DoBlah方法可以抛出BlahException或扩展它的任何其他异常。
如果它是一个检查的异常,编译器将要求它们在try / catch块中调用此方法。如果它没有被检查,他们可以选择不捕获异常,但是他们必须注意到,如果它们不会在调用堆栈上进一步冒泡。
它没有说明任何关于未检查的异常,如NullPointException或错误。这些都可以随时抛出。它们在throws子句中不是必需的。
此代码显示它的工作原理:
ExceptionDemo.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");
}
}
CheckedException.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);
}
}