一.异常
异常(exception)是在运行过程中代码序列中产生一种例外情况,之前学习的过程中使用If…else…来解决异常.
异常和错误是两种不同的概念
常见的异常类型有以下几种:
1.try,catch,finally及多重catch实例代码如下:
package cn.zc.异常类;
public class try_catch {
public static void main(String[] args) {
try {
int num = 5/0;
System.out.println(num);
System.out.println("测试是否跳过");
String str = null;
System.out.println(str.length());
}catch (ArithmeticException e){
System.out.println("除数不能为0");
}catch (NullPointerException e){
System.out.println("值不能为空");
}catch (Exception e){
System.out.println("程序异常");
}finally {
System.out.println("资源回收");
}
System.out.println("测试是否执行");
}
}
运行结果:
由运行结果可知:
1.try方法里面的语句如果出现异常,则跳过后续代码,直接进入catch进行判断.
2.finally是用来进行比如释放内存等资源回收的代码,是必定执行的
3.一个try 代码块后面跟随多个 catch 代码块的情况就叫多重捕获(多重catch),最后一个catch一般使用Exception来捕获异常.
将0改为2后,运行结果如图:
2.嵌套catch:
package cn.zc.异常类;
import java.util.Scanner;
//嵌套catch
public class nest_catch {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一个除数:");
try {
int a = scanner.nextInt();
int num = 5/a;
try {
String str = null;
System.out.println(str.length());
}catch (NullPointerException e){
System.out.println("值不能为空");
}
}catch (ArithmeticException e){
System.out.println("除数不能为0");
}finally {
System.out.println();
System.out.println("资源回收");
}
System.out.println("继续执行");
}
}
输入为0时运行如下:
输入不为0时:
二.throw throws
如果一个方法没有捕获到一个检查性异常,那么该方法必须使用 throws 关键字来声明,跟在方法后。也可以使用 throw 关键字抛出一个异常,无论它是新实例化的还是刚捕获到的
三.自定义异常
自己设定一个异常,只要满足条件就会运行
四.throw throws和自定义异常综合应用
代码实例如下:
public class CustomException extends Exception{
public CustomException(){
super();
}
public CustomException(String s){
super(s);
}
}
//自定义异常实例
import java.util.Scanner;
public class TestException {
public static void main(String[] args) {
try {
show();
} catch (CustomException custom) {
System.out.println("年龄不能为负数或大于200");
}
}
public static void show() throws CustomException {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入年龄:");
int age = scanner.nextInt();
if (age>200||age<0){
throw new CustomException();
}
}
}