java异常简介
java异常是java提供的一种识别及响应错误的一致性机制
java异常机制可以使程序中的异常代码和正常业务代码分离, 保证程序代码更加准确, 提高程序的健壮性.
java异常机制用到的几个关键字 : try, catch, finally, throws, throw
- try : 用于监听, 将要被监听的代码放在try语句块内, 当try语句块内发生异常时, 异常就被抛出.
- catch : 用于捕获异常, 捕获try语句块中发生的异常.
- finally : 用于回收在try块里打开的物理资源(如数据块连接, 网络连接和磁盘文件)只有finally块执行完成之后, 才会回来执行try或者catch块中的return或者throw语句. 如果finally中使用了return或者throw等终止方法的语句, 则就不会跳回执行, 直接停止.
- throw : 用于抛出异常.
- throws : 用在方法签名中, 用于声明该方法可能抛出的异常
try和catch的基本用法 :
public class Demo1 {
public static void main(String[] args) {
try {
int i = 10/0;
System.out.println("i="+i);
} catch (ArithmeticException e) {
System.out.println("Caught Exception");
System.out.println("e.getMessage(): " + e.getMessage());
System.out.println("e.toString(): " + e.toString());
System.out.println("e.printStackTrace():");
e.printStackTrace();
}
}
}
运行结果 :
Caught Exception
e.getMessage(): / by zero
e.toString(): java.lang.ArithmeticException: / by zero
e.printStackTrace():
java.lang.ArithmeticException: / by zero
at Demo1.main(Demo1.java:6)
在try语句块中有除数为0的操作, 该操作会抛出java.lang.ArithmeticException异常, 通过catch对异常进行捕获.观察结果我们可以发现, 并没有执行System.out.println("i="+i) 这说明try语句块发生异常之后, try语句块中的剩余内容就不会再被执行了.
常会出现的问题 :
用户没有输入初始化参数 : ArrayIndexOutOfBoundsException
用户输入的不是数字 : NumberFormatException
被除数为0 : ArithmeticException
finally的基本用法
在上面的示例中再加上finally块
public class Demo2 {
public static void main(String[] args) {
try {
int i = 10/0;
System.out.println("i="+i);
} catch (ArithmeticException e) {
System.out.println("Caught Exception");
System.out.println("e.getMessage(): " + e.getMessage());
System.out.println("e.toString(): " + e.toString());
System.out.println("e.printStackTrace():");
e.printStackTrace();
} finally {
System.out.println("run finally");
}
}
}
运行结果 :
Caught Exception
e.getMessage(): / by zero
e.toString(): java.lang.ArithmeticException: / by zero
e.printStackTrace():
java.lang.ArithmeticException: / by zero
at Demo2.main(Demo2.java:6)
run finally
可以看到, 最终执行了finally语句块
对于以上三个关键字, 可以出现的组合 : try..catch try..finally try..catch..finally
throws和throw的基本用法
throws用于声明抛出的异常, throw是用于抛出异常
class MyException extends Exception {
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class Demo3 {
public static void main(String[] args) {
try {
test();
} catch (MyException e) {
System.out.println("Catch My Exception");
e.printStackTrace();
}
}
public static void test() throws MyException{
try {
int i = 10/0;
System.out.println("i="+i);
} catch (ArithmeticException e) {
throw new MyException("This is MyException");
}
}
}
运行结果 :
Catch My Exception
MyException: This is MyException
at Demo3.test(Demo3.java:24)
at Demo3.main(Demo3.java:13)
MyException是继承于Exception的子类, test()的try语句块中产生的ArithmeticException异常(除数为0), 并在catch中捕获异常, 接着抛出MyException异常, main()方法对test()中抛出的MyException进行捕获处理