异常
异常(exception)是在运行过程中代码序列中产生一种例外情况。
常见的异常类型:
Java异常处理通过5个关键字控制:try、catch、 throw、throws和 finally。
1.try-catch结构:
try{
代码A
代码B
}catch(ExceptionType e){
异常处理
}
代码C
实例:
public static void main(String[] args) {
try{
int num = 5/0;
System.out.println(num);
}catch (ArithmeticException e){
System.out.println("除数不能为零");
}finally {
System.out.println("回收代码资源");
}
try{
String string = null;
System.out.println(string.length());
}catch (NullPointerException e){
System.out.println("数值不能为空");
}finally {
System.out.println("回收代码资源");
}
System.out.println("程序继续执行");
}
结果如下:
2.多重catch块:
实例:
public static void main(String[] args) {
try {
int num = 5/0;
System.out.println(num);
String string = null;
System.out.println(string.length());
}catch (ArithmeticException e){
System.out.println("除数不能为零");
}catch (NullPointerException e){
System.out.println("数值不能为空");
}finally {
System.out.println("回收代码资源");
}
}
结果是:
3.try-catch嵌套:
实例:
public static void main(String[] args) {
try{
try {
int num = 5/0;
System.out.println(num);
String string = null;
System.out.println(string.length());
}catch (NullPointerException e){
System.out.println("数值不能为空");
}
}catch (ArithmeticException e){
System.out.println("除数不能为零");
}finally {
System.out.println("回收代码资源");
}
}
结果是:
4.throw,throws和自定义异常:
package cn.zbw.exception;
public class MyException extends Exception {
public MyException(){
super();
}
public MyException(String string){
super(string);
}
}
public static void main(String[] args) {
try{
try {
int num = 5/0;
System.out.println(num);
String string = null;
System.out.println(string.length());
}catch (NullPointerException e){
System.out.println("数值不能为空");
}
}catch (ArithmeticException e){
System.out.println("除数不能为零");
}finally {
System.out.println("回收代码资源");
}
}
结果是:
总结:
1、运行时发生的错误称为异常;
2、Java使用try,catch,throw,throws和finally来处理Java异常;
3、被监控的代码写在try块中,用来捕获和处理异常的代码写在catch块中,finally中放置必须要执行的代码;
4、要手动引发异常,可以使用关键字throw。抛到方法外部的任何异常都必须用throws子句指定。