一、异常的基本概念
1.异常处理格式:
try {
//可能出现异常的语句
}catch(异常类 异常对象){
//异常处理语句
}catch(异常类 异常对象){
//异常处理语句
}
finally {
//一定会执行的程序代码
}
其中:catch至少一个,finally可有可无。
2. 异常类的继承结构:
Java异常结构中最常用的两个类:Exception和Error,他俩都是Throwable的子类。
Exception:一般指程序中的问题,可以用try...catch...捕获。
Error:一般指JVM中的错误,程序中无法处理。
3.Java的异常处理机制
1)一旦产生异常,则首先会产生一个异常类的实例化对象。
2)在try语句中对此异常对象进行捕捉。
3)产生的异常对象与catch中的各个异常类进行匹配,如果匹配成功则执行catch语句中的代码。
4.示例:
public class Test {
public static void main(String args[]) {
System.out.println("**********start***********");
int i=0;
int j=0;
try {
String str1 = args[0];
String str2 = args[1];
i = Integer.parseInt(str1);
j = Integer.parseInt(str2);
int temp = i/j;
System.out.println("连个数字相除的结果:"+temp);
}catch(ArithmeticException e) {
System.out.println("算术异常:" + e);
/*除了用System.out.println(异常对象)的方式打印异常外,
还可以直接使用Exception类的printStackTrace()方法输出完整的异常信息:
e.printStackTrace();
*/
}catch(NumberFormatException e) {
System.out.println("数字转换异常:"+e);
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界异常:"+e);
}catch(Exception e){//利用多态向上转型,让其他的异常都用父类Exception接收
System.out.println("其他异常:"+e);
}finally {
System.out.println("**********end***********");
}
}
}
注意:1)e.printStackTrace() 输出异常信息
2)catch(Exception e){ } 捕获所有异常。尽可能详细,且如果要用Exception,放最后一个catch中。
3)不可以用Throwable,因为它包括error,程序中只捕获Exception就好。
二、throws与throw关键字
1.throws关键字:
1)throws Exception声明的方法,内部可以不处理异常。但是调用时要处理。
2)示例:
public class Test {
public static void main(String args[]) {
try {
div(2,5);
} catch (Exception e) {
e.printStackTrace();
}
}
public static int div(int i , int j) throws Exception{
int temp = i/j;
return temp;
}
}
2.throw关键字:‘
1)可以使用throw主动抛出一个异常,抛出时直接抛出异常类的实例化对象即可。
2)示例:
public class Test {
public static void main(String args[]) {
try {
throw new Exception("手动产生一个异常类的实例化对象");
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.范例——throw和throws的应用
public class Test {
public static void main(String args[]) {
Math m = new Math();
try {
m.div(3, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Math{
public int div(int i, int j) throws Exception{
System.out.println("开始计算");
int temp = 0;
try {
temp = i/j;
}catch(Exception e) {
throw e;
}finally {
System.out.println("结束计算");
}
return temp;
}
}
三、Exception类与RuntimeException类
Excpetion在程序中必须用try...catch进行处理。
RuntimeException可以不用try...catch进行处理,但是如果有异常产生,将由JVM处理。
四、自定义异常类
1.方法:继承Exception类即可。
2.示例:
public class Test {
public static void main(String args[]) {
try {
throw new MyException("自定义异常");
}catch(Exception e){
e.printStackTrace();
}
}
}
class MyException extends Exception{
public MyException(String msg) {
super(msg);
}
}
五、断言
1.作用:判断某一个结果的返回值是否正确。
2.格式:
assert boolean 表达式;
assert boolean 表达式 :详细的信息
如果boolean表达式结果为true,则什么错误信息都不会显示;
如果为false,则会提示错误信息。如若没有声明详细的信息,则使用默认的错误提示方式。
3.示例:
public class Test {
public static void main(String args[]) {
int i[] = {1,2,3};
assert i.length == 0 : "数组长度不为0" ;
}
}
注意:运行时run as → Run Configurations → 在参数的VM argument中写 -ea