10day
异常机制
exception
-
检查性异常:最具代表性的检查性异常使用户错误或问题引起的异常
-
运行时异常:运行时异常时可能被程序员避免的异常
-
错误error:错误不是异常,而是脱离程序员的控制的问题
异常处理框架:Java把异常当做对象来处理,并定义一个基类java.lang.Throwable作为所有异常的超类
Error:Error类对象由Java虚拟机生成并抛出,大多数错误与代码编写者所执行的操作无关
-
ArrayIndexOutOfBoundsException(数组下标越界)
-
NullPointerException(空指针)
-
ArithmeticException(算术异常)
-
MissingResourceException(丢失资源)
-
ClassNotFoundException(找不到类)
这些异常可以选择捕获处理,也可以不处理
抛出异常
捕获异常
public static void main(String[] args) {
int a=0;
int b=1;
try {
System.out.println(b/a);
}catch(ArithmeticException e){//捕获异常
System.out.println("程序出现异常,变量b不能为0");
}finally {//可以不要
System.out.println("finally");
}
}
public static void main(String[] args) {
int a=0;
int b=1;
//捕获异常
try { //范围
System.out.println(b/a); //由
}catch (Error t){ //小
System.out.println("Error"); //到
}catch (Exception o){ //大
System.out.println("Exception");
}
catch(Throwable e){//捕获异常 catch(想要捕获的异常类型)
System.out.println("Throwable");
}finally {//可以不要
System.out.println("finally");
}
}
生成异常
关键字:try、catch、finally、throw(在方法中)、throws(抛出异常)
public static void main(String[] args) {
int a=0;
int b=1;
//生成异常 Ctrl+Alt+t
try {
System.out.println(b/a);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) {
int a;
int b;
try {
new Test1().test(1,0);
} catch (ArithmeticException e) {
e.printStackTrace();//捕获之后程序会继续进行
}
}
public void test(int a,int b) throws ArithmeticException{
if (a==0){
throw new ArithmeticException();//主动抛出异常 一般在方法中使用
}
System.out.println(a/b);
}
自定义异常
使用Java内置的异常类可以描述出在编程中的大部分异常,除此之外,用户还可以自定义异常。用户自定义异常类,只需要继承Exception类即可。
使用自定义异常类,大体可分为以下几个步骤:
-
创建自定义异常类
-
在方法中通过throw关键字抛出异常对象
-
如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作
-
再出现异常方法的调用者中捕获并处理异常。
//Exception
public class MyException extends Exception{
//传递数字
private int detail;
public MyException(int a){
this.detail=a;
}
//toString异常的打印信息
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(11);
} catch (MyException e) {
System.out.println("MyException=>"+e);
}
}
}

浙公网安备 33010602011771号