1.throws 捕获并向外抛出异常
package 拓展作业;
public class Test2 {
public static void main(String[] args) throws Exception {
int result = divide(4, 0);
System.out.println(result);
}
public static int divide(int x, int y) throws Exception {
int result = x / y;
return result;
}
}
如此向外抛出会直接抛出异常信息
结果:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at 拓展作业.Test2.divide(Test2.java:10)
at 拓展作业.Test2.main(Test2.java:5)
2.try,catch是内部捕获异常并做自定义处理
package 拓展作业;
public class Test2 {
public static void main(String[] args) {
int result;
try {
result = divide(4, 0);
System.out.println(result);
} catch (Exception e) {
System.out.println("除数为0错误");//自定义处理方式
}
}
public static int divide(int x, int y) throws Exception {
int result = x / y;
return result;
}
}
结果:
除数为0错误
3.finally 是无论是否有异常都会被处理的语句,除非在 finally 前存在被执行的
(在最后必须进行的处理,做收尾工作)
4.throw 抛出异常
package 拓展作业;
public class Test2 {
public static void main(String[] args) {
String s = "abc";
if (s.equals("abc")) {
throw new NumSameException("字符相同");
} else {
System.out.println(s);
}
}
}
class NumSameException extends NumberFormatException {
public NumSameException() {
super();
}
public NumSameException(String s) {
super(s);
}
}
结果:
Exception in thread "main" 拓展作业.NumSameException: 字符相同
at 拓展作业.Test2.main(Test2.java:8)
throw是语句抛出一个异常。
语法:throw 异常对象;