异常(Excoption)
分类
- Throwable
- 错误Error(不可处理)
- VirtuMachineError
- AWTError
- 异常Exception(可以处理)
- IOException:
- RuntimeException:
- 错误Error(不可处理)
异常处理(try,catch,finally,throw,throws)
捕获异常
格式
try{
异常语句
}catch(Exception e){
}finally{
一定会执行的代码
}
例子
package ooday05;
//异常捕获
public class Demo {
/* public static void main(String[] args) {
int a=1;
int b=0;
System.out.println(a/b);//异常:Exception in thread "main" java.lang.ArithmeticException:
}*/
public static void main(String[] args) {
int a=1;
int b=0;
try {//监控区域
System.out.println(a/b);
}catch (ArithmeticException e){//捕获异常 ArithmeticException:捕获的异常类型
System.out.println("程序程序异常,变量不能为0");
}finally {//处理善后工作
System.out.println("finally");
}
}
}
package ooday05;
//异常捕获
public class Demo01 {
public static void main(String[] args) {
int a=1;
int b=0;
try {
System.out.println(a/b);//快捷键:ctrl+alt+T
} catch (Exception e) {
System.exit(1);//结束运行
e.printStackTrace();//打印错误的栈信息
} finally {
System.out.println("finally");
}
}
}
抛出异常
throws关键字
package ooday05;
//抛出异常
public class Demo02 {
public static void main(String[] args) throws Exception {
try {
n();
} catch (ArithmeticException e) {
System.out.println(e);
} finally {
System.out.println("finally");
}
}
public static void n() throws ArithmeticException{
int a=1;
int b=0;
System.out.println(a/b);
}
}
throw关键字
package ooday05;
//抛出异常 throw
public class Demo03 {
public static void main(String[] args) {
try {
throw new Exception("实例化异常对象");
} catch (Exception e) {
System.out.println(e);
}
}
}
自定义异常
直接继承Exception就可以来完成自定义异常类
package ooday05;
class MyException extends Exception{
public MyException(String msg){
super(msg);
}
}
public class Demo04 {
public static void main(String[] args) {
try {
throw new MyException("自定义异常");
} catch (Exception e) {
System.out.println(e);
}
}
}