文章目录
1. 所有异常都继承Throwable
类
2. 分类:
Error:一般是与虚拟机有关的问题,它无法恢复或不可捕获。
应用程序不处理。不应使用catch块
来 捕获。
RunTimeException:由于程序错误导致的异常。
IOException: 程序没有问题,由于I/O错误导致的异常。
派生于Error,RunTimeException的异常 统称非受查异常;所有其他的称为受查异常。
3. 为什么要处理异常:
出现异常,不合理的处理会导致程序终止执行。
4. 异常处理格式
try{
//业务实现代码 ;
} [catch (异常类 形参) {
} ... ]
[finally {
异常的出口
}]
可以出现的组合:try..catch 、 try..finally 、 try..catch..finally
*** 不管是否产生异常,try里的业务代码块最后都会走finally出去。
*** 异常处理这块,try,catch,finally
后面的{}
都不能省
5.完整异常信息的取得
e.printStackTrace();
public class TestException {
public static void main(String[] args) {
System.out.println("1.数学运算开始前");
try {
System.out.println("2.进行数学运算的结果: " + (10/0));
} catch (ArithmeticException e) {
System.out.print("3.取得异常完整信息: ");
e.printStackTrace();
} finally {
System.out.println("4.不管是否产生异常,都会走出口,执行这一步");
}
}
}
5.1 常见的异常:
用户没有输入初始化参数:ArrayIndexOutOfBoundsException
用户输入的不是数字: NumberFormatException
被除数为0:ArithmeticException
public class TestException {
public static void main(String[] args) {
System.out.println("1.数学运算开始前");
//1.ArithmeticException
// int x = Integer.parseInt("1");
// int y = Integer.parseInt("0");
//2.NumberFormatException
// int x = Integer.parseInt("1");
// int y = Integer.parseInt("str");
//3. ArrayIndexOutOfBoundsException
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
try {
System.out.println("2.进行数学运算的结果: " + (x/y));
} catch (ArithmeticException e) {
System.out.print("3.取得异常完整信息: ");
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} finally {
System.out.println("4.不管是否产生异常,都会走出口,执行这一步");
}
}
}
6. throws
throw
关键字
6.1 throws
用在定义方法上
6.1.1 用在普通方法声明中,调用该方法时,需要在调用处进行异常处理
public static void main(String[] args) {
try {
System.out.println(divid(10,0));
} catch (Exception e) {
e.printStackTrace();
}
}
public static int divid(int x ,int y) throws Exception {
return x/y;
}
6.1.2 用在main方法声明中,交由JVM处理
public static void main(String[] args) throws Exception{
System.out.println(10/0);
}
6.2 throw
用在方法中 - 直接编写在语句中
一般结合if
语句使用
public static void main(String[] args) throws Exception{
Object obj = new Object();
obj = "str";
if (obj != null) {
throw new Exception("异常");
}
}
6.3 ** throws
与throw
的区别
throws
:用在方法声明上,告诉用户本方法可能产生的异常,并且不一定处理。
throw
:用在方法内部,一般结合 if
语句来手工抛出异常
- ***** RunTimeException
使用RuntimeException定义的异常类可以不需要强制性进行异常处理
Exception
与RunTimeException
的区别
(1)Exception
是 RunTimeException
的父类
使用Exception
定义的异常都要求必须使用异常处理,
而使用RuntimeException
定义的异常可以由用户选择性的来进行异常处理。(例如Integer.praseInt()
)
(2) 常见的RuntimeException:
ClassCastException
、
NullPointerException
,
IndexOutOfBoundException
等。