the fifth day003Exception
异常exception
- 内存满了
- 用户输入不合法内容
- 程序打开一个不存在的文件
// System.out.println(33/0);//java.lang.ArithmeticException: / by zero
System.out.println()//Error ;冒号缺失
RuntimeException
ArrayIndeOutOfBoundException 数组下标
NullPointerException 空指针
ArithmeticException 算术异常
MissingResouceException 丢失资源
ClassNotFoundException 类找不到
这些都是运行时异常可以捕获,
try catch finally throw throws
-
public static void main(String[] args) { int a = 0; int b = 1; try{ double c = b/a; System.out.println(c); }catch (ArithmeticException e){ System.out.println("程序异常,变量作为除数不能为0"); }catch (Exception e){ System.out.println("异常捕获多个时需要从小到大,否则先大后小会失效"); }finally { System.out.println("默认结束关闭一些东西"); } try{ a();//java.lang.StackOverflowError 堆栈溢出错误 无限循环调用 }catch (Error e){ System.out.println("Error错误用异常是无法捕获的,需要用Error"); } } public static void a(){ b(); } public static void b(){ a(); }
自定义异常
public class MyException extends Exception {
//自定义异常继承了最大的异常父类
//传递数字小于100抛出一个异常 , 实现构造类打印消息 快捷键alt + shift + 0 constructor
private int detail;
@Override
public String toString() {//被捕获时会打印此信息
return "MyException{" +
"detail=" + detail +
'}';
}
public MyException(int a) {
this.detail = a;
}
public MyException(String message) {
super(message);
}
}
//测试自定义异常
public class TestException {
static void test (int a ) throws MyException{
if( a < 100){
throw new MyException(a);
}
}
public static void main(String[] args) {
try {
test(150);
System.out.println("正常运行");
}catch (MyException m){
System.out.println("c参数"+m);
}
}
}