异常处理
java虚拟机的默认处理方案会在程序出现异常时结束程序,而实际项目中某一部分出现异常不应该影响后面程序的执行,所以要自己处理异常。
一. Java的异常类
1. 编译时异常与运行时异常的区别
2. Throwable的成员方法
异常祖先类Throwable的成员方法
public class ThrowableTest {
public static void main(String[] args) {
System.out.println("开始");
method();
System.out.println("结束");
}
private static void method() {
try {
int a[]={
1,2};
System.out.println(a[3]);
}catch (ArrayIndexOutOfBoundsException e){
// System.out.println(e.getMessage());//3
// System.out.println(e.toString());//java.lang.ArrayIndexOutOfBoundsException: 3
e.printStackTrace();
/*
java.lang.ArrayIndexOutOfBoundsException: 3
at _3Exception.ThrowableTest.method(ThrowableTest.java:25)
at _3Exception.ThrowableTest.main(ThrowableTest.java:18)
*/
}
}
}
二. 处理异常
如果程序出现问题,我们需要自己来处理,有两种方案:
- try…catch
- throws
1.异常处理之try…catch
格式:
try{
可能出现异常的代码;
}catch(异常类名 变量名){
异常处理代码;
}finally{
必须执行的代码;
}
public class ExceptionTest1 {
public static void main(String[] args) {
try {
int a[]={
1,2};
System.out.println(a[2]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("越界");
e.printStackTrace();
}
System.out.println("结束");
}
}
2. 异常处理之throws
虽然我们通过try…catch…可以对异常处理,但不是所有情况我们都有权限进行异常处理,也就是说,有些时候可能出现的异常我们处理不了,这个时候怎么办呢?
针对这个情况,java提供throws解决方案
public class ThrowsTest {
public static void main(String[] args) {
System.out.println("开始");
method1();//运行时异常如果需要程序继续执行还需要try catch
try {
method2();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println("结束");
}
//运行时异常
public static void method1() throws ArrayIndexOutOfBoundsException{
int a[] = {
1, 2};
System.out.println(a[2]);
}
//编译时异常
public static void method2() throws ParseException {
String s="2048-08-01";
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=sdf.parse(s);//此处有编译异常
System.out.println(d);
}
}
- 注意
抛出异常本身没有实质性的处理,真正的处理还是要进行try,catch处理
三. 自定义异常
1. 步骤
- 自定义一个自定义异常类,必须继承Exception类
- 在可能出现异常的方法头使用throws声明该异常
- 在方法体中出现异常的地方使用throw抛出该自定义异常对象
2. throws和throw的使用
Java提供了throws处理方案。有可能发生异常的语句出现再哪个函数里,就要在该函数的函数首部通过throws声明该异常,在出现问题的情况下通过throw抛出异常。
格式:
返回值类型 方法名称 throws 异常类名{
if(发生异常)
throw 异常类对象;
}
3. throws和throw的区别
4.案例
- 自定义异常类
通过super调用父类Exception的构造方法
//异常类,固定格式
public class ScoreException extends Exception {
//继承Exception类,编译异常
ScoreException(){
}
ScoreException(String message){
super(message);//传给祖先类
}
}
- 可能产生异常的地方
//会产生异常的地方
public class Teacher {
public static void checkScore(int score) throws ScoreException {
if (score <0 ||score>100){
throw new ScoreException(score+":成绩不符合规范");//抛出异常对象
}else {
System.out.println("成绩符合规范");
}
}
}
- 测试
//测试
public class TeacherTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("输入分数:");
int s=in.nextInt();
Teacher t = new Teacher();
try {
t.checkScore(s);//编译异常,需要用try catch抓起来
} catch (ScoreException e) {
e.printStackTrace();
}
}
}