通过抛出已检查的异常,可以强制调用方在一个catch块中处理该异常。如果一个方法抛出一个检查异常,它必须在方法声明中声明它抛出了异常。
除java.lang.Error,java.lang.RuntimeException及其子类指示的那些异常外,所有异常都是经过检查的异常。
运行时异常是应用程序内部的特殊情况,应用程序通常无法预期或从中恢复。运行时异常是由java.lang.RuntimeException及其子类指示的异常。
RuntimeException称为未经检查的异常。不需要在方法声明中声明未经检查的异常。
package org.nhooo.example.fundamental; import java.io.File; import java.io.IOException; public class ExceptionExample { public static void main(String[] args) { // 您必须捕获已检查的异常,否则会得到 // 编译时错误。 try { ExceptionExample.checkFileSize("data.txt"); } catch (IOException e) { e.printStackTrace(); } // 未经检查的异常不需要您抓住 // 它,它不会产生编译时错误。 ExceptionExample.divide(); } /** * 此方法引发 Checked Exception,因此必须声明方法声明中的异常 * * @param fileName given file name * @throws IOException when the file size is to large. */ public static void checkFileSize(String fileName) throws IOException { File file = new File(fileName); if (file.length() > Integer.MAX_VALUE) { throw new IOException("File is too large."); } } /** * 此方法抛出 RuntimeException。 * 不需要在方法声明中声明 Exception * * @return a division result. * @throws ArithmeticException when arithmetic exception occurs. */ public static int divide() throws ArithmeticException { int x = 1, y = 0; return x / y; } }