(一) 使用 try…catch…finally 语句处理异常
package work03;
public class Demo03 {
public static void main(String[] args) {
int a = 100, b = 0, c;
try {
c = a / b;
System.out.println("c=" + c);
} catch (ArithmeticException e) {
System.out.println("catched!");
System.out.println("catch ArithmeticException message:"
+ e.getMessage());
System.out.println("catch ArithmeticException toSting():"
+ e.toString());
// e.toString()获取的信息包括异常类型和异常详细消息,而e.getMessage()只是获取了异常的详细消息字符串。
e.printStackTrace();//异常打印的线程执行的时间是随机的。
} finally {
System.out.println("finally!");
}
}
}
(二) 使用 throw 语句抛出异常、使用 throws 子句抛弃异常
package work03;
public class Demo03 {
static void throwProcess(Object o) throws NullPointerException {
if (o == null)
throw new NullPointerException("空指针异常");
System.out.println(o.toString());
}
public static void main(String args[]) {
Object p = null;
try {
throwProcess(p);
} catch (NullPointerException e) {
System.out.println("捕获:" + e);
}
}
}
/*捕获:java.lang.NullPointerException: 空指针异常
*/
package work03;
public class Demo03 {
static void throwProcess() {
try {
throw new NullPointerException("空指针异常");
} catch (NullPointerException e) {
System.out.println("\n在throwProcess 方法中捕获一个" + e.getMessage());
throw e;
}
}
public static void main(String args[]) {
try {
throwProcess();
} catch (NullPointerException e) {
System.out.println("再次捕获:" + e);
}
}
}
/*
在throwProcess 方法中捕获一个空指针异常
再次捕获:java.lang.NullPointerException: 空指针异常
*/
(三)创建自定义异常类