您在try-catch块中捕获的异常必须已通过调用的方法引发。您可以使用包含throw关键字和后跟异常对象的语句引发异常。此异常对象是Throwable该类的任何子类的实例。
在下面的示例中,我们有两个引发异常的静态方法。第一种方法,当除法器为零值整数时,throwException()将抛出ArithmethicException。如果date参数值为,printDate(Date date)则第二种方法将抛出。NullPointerExceptionnull
package org.nhooo.example.fundamental;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ThrowExample {
public static void main(String[] args) {
try {
ThrowExample.throwException();
} catch (Exception e) {
e.printStackTrace();
}
try {
ThrowExample.printDate(null);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void throwException() {
int x = 6;
int[] y = {3, 2, 1, 0};
for (int i = 0; i < y.length; i++) {
if (y[i] == 0) {
// 即将发生时引发ArithmeticException
// 除以零。
String message = String.format(
"x = %d; y = %d; a division by zero.",
x, y[i]);
throw new ArithmeticException(message);
} else {
int z = x / y[i];
System.out.println("z= " + z);
}
}
}
public static void printDate(Date date) {
if (date == null) {
throw new NullPointerException("Date cannot be null.");
}
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Date: " + df.format(date));
}
}