异常
Erro和Exception
捕获和抛出异常
package exception;
public class Demo {
public static void main(String[] args) {
//假设要捕获多个异常: 从小到大
int a = 1;
int b = 0;
try {
if (b == 0) {
throw new ArithmeticException(); //主动抛出异常
}
System.out.println(a / b);
//监控区域
System.out.println(a / b);
} catch (ArithmeticException e) { //捕获异常类型
System.out.println("程序出现错误");
} finally {//善后工作
System.out.println("finally");
}
}
}
package exception;
public class Demo2 {
public static void main(String[] args) {
int a = 1;
int b = 0;
try {
System.out.println(a/b);
} catch (Exception e) {
e.printStackTrace(); //打印错误的栈信息
} finally {
System.out.println("finally");
}
}
}
package exception;
public class Demo3 {
public static void main(String[] args) {
try {
new Demo3().test(1, 0);
} catch (ArithmeticException e) {
e.printStackTrace();
}
}
public void test(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException(); //主动抛出异常,一般在方法中使用
}
}
}
自定义异常
package exception;
//自定义的异常类
public class MyException extends Exception {
//传递数字>10
private int delail;
public MyException(int a) {
this.delail = a;
}
//toString
//异常的打印信息
@Override
public String toString() {
return "MyException{" +
"delail=" + delail +
'}';
}
}
package exception;
public class test {
static void test(int a) throws MyException {
System.out.println("传递的数值:" + a);
if (a > 10) {
throw new MyException(a);//抛出
}
System.out.println("ok");
}
public static void main(String[] args) {
try {
test(50);
} catch (MyException e) {
System.out.println("MyException==>" + e);
}
}
}
try {
test(50);
} catch (MyException e) {
System.out.println("MyException==>" + e);
}
}
}
源代码
GitHub:https://github.com/YixinWen/java.git (javaSE 分支)
Gitee(码云):https://gitee.com/wenyixin666/java.git (javaSE 分支)