int a=1;
int b=0;
try { //监控区域
System.out.println(a/b);
}catch (ArithmeticException e){
System.out.println("程序出现异常,我在这里捕获了!");
}finally {
System.out.println("fianlly:我负责处理善后工作,无论出不出异常我都会走");
}
public static void main(String[] args) {
try { //监控区域
new Student().test(1,0);
} catch (Exception e) {
e.printStackTrace();
}
}
//方法上抛出异常,假设在这个地方处理不了异常 在方法上用throws
public void test (int a ,int b) throws Exception{
if (b == 0) {
//throw 方法内部抛出异常
throw new ArithmeticException();
}
}
public class Exception extends java.lang.Exception {
//传递数字>10
private int detial;
public Exception(int detial) {
this.detial = detial;
}
@Override
public String toString() { //异常的打印信息
return "Exception{" +
"detial=" + detial +
‘}‘;
}
}
public class Test {
//可能会存在异常的方法
static void test( int a) throws Exception {
System.out.println("传递的参数为:"+a);
if (a >10) {
throw new Exception(a);
}else {
System.out.println("输入数字没有大于10");
}
}
public static void main(String[] args) {
try {
test(12);
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------
传递的参数为:12
Exception{detial=12}
at Scanner.OOp.Exception.Test.test(Test.java:8)
at Scanner.OOp.Exception.Test.main(Test.java:16)
原文:https://www.cnblogs.com/suwenwu/p/15017409.html