java基础知识点05_异常
程序员文章站
2024-02-01 08:15:46
...
java基础知识点05_异常
异常的超类:java.lang.Throwable
异常处理机制
捕获:
int a = 1;
int b = 0;
try {
System.out.println(a/b);
} catch (ArithmeticException e) {
System.out.println("程序出现异常:变量b不能为0");
}finally {
System.out.println("finally....");
}
public static void main(String[] args) {
try {
a();
} catch (*Error e) {
System.out.println("程序出现错误:*Error");
}finally {
System.out.println("finally....");
}
}
public static void a() {
b();
}
public static void b() {
a();
}
抛出:
- 系统自动抛出:
public static void main(String[] args) {
System.out.println(1/0);
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
- 开发者主动抛出:
public static void main(String[] args) {
int a = 1;
int b = 0;
if(b==0) {
throw new ArithmeticException();
}else {
System.out.println(a/b);
}
}
Exception in thread "main" java.lang.ArithmeticException
自定义异常:
public class MyException extends Exception{
//传递数字,如果数字大于10,则抛出异常
private int detail;
public MyException(int a) {
this.detail = a;
}
@Override
public String toString() {
return "MyException{"
+ "detail=}"
+ detail
+ "}";
}
}
public class demo01 {
static void test(int a) throws MyException {
if(a>10) {
throw new MyException(a);
}
System.out.println("okkkkkkkkkkk");
}
public static void main(String[] args) {
try {
test(23);
} catch (MyException e) {
System.out.println(e);
e.printStackTrace();
}
}
}