异常学习
异常介绍
●基本概念
Java语言中,将程序执行中发生的不正常情况称为"异常”。(开发过程中的语法
错误和逻辑错误不是异常)
执行过程中所发生的异常事件可分为两类
- Error(错误): Java虚拟机无法解决的严重问题。如: JVM系统内部错误、资源
耗尽等严重情况。比如: StackOverflowError[栈溢出]和OOM(out of
memory), Error 是严重错误,程序会崩溃。 - Exception:其它因编程错误或偶然的外在因素导致的一般性问题,可以使用针
对性的代码进行处理。例如空指针访问,试图读取不存在的文件,网络连接中
断等等,Exception 分为两大类:运行时异常[]和编译时异常[]。
常见的运行时异常
常见的运行时异常包括
- NullPointerException空指针异常
- ArithmeticException数学运算异常
- ArrayIndexOutOfBoundsException数组下标越界异常
- ClassCastException类型转换异常
- NumberFormatException数字格式不正确异常[]
编译异常
介绍
编译异常是指在编译期间,就必须处理的异常,否则代码不能通过编译。
常见的编译异常
- SQLException //操作数据库时,查询表可能发生异常
- IOException //操作文件时,发生的异常
- FileNotFoundException //当操作一个不存在的文件时,发生异常
- ClassNotFoundException //加载类,而该类不存在时,异常
- EOFException //操作文件到文件末尾,发生异常
- IllegalArguementException //参数异常
try- catch异常处理
try-catch方式处理异常注意事项
- 如果异常发生了,则异常发生后面的代码不会执行,直接进入到catch块.
- 如果异常没有发生,则顺序执行try的代码块,不会进入到catch.
- 如果希望不管是否发生异常,都执行某段代码(比如关闭连接,释放资源等)
则使用如下代码- finally {}
try-catch-finally执行顺序小结
- 如果没有出现异常,则执行try块中所有语句,不执行catch块中语句,如
果有finally,最后还需要执行finally里面的语句 - 如果出现异常,则try块中异常发生后,try块剩 下的语句不再执行。将执
行catch块中的语句,如果有finally, 最后还需要执行finally里面的语句!
throws异常处理
基本介绍
- 如果一个方法(中的语句执行时)可能生成某种异常,但是并不能确定如何
处理这种异常,则此方法应显示地声明抛出异常,表明该方法将不对这些
异常进行处理,而由该方法的调用者负责处理。 - 在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异
常类型可以是方法中产生的异常类型,也可以是它的父类。
注意事项和使用细节
- 对于编译异常,程序中必须处理,比如try- catch或者throws
- 对于运行时异常,程序中如果没有处理,默认就是throws的方式处理
- 子类重写父类的方法时,对抛出异常的规定:子类重写的方法,所抛出的异常类型要
么和父类抛出的异常一致,要么为父类抛出的异常的类型的子类型 - 在throws过程中,如果有方法try-catch ,就相当于处理异常,就可以不必throws
自定义异常
●基本概念
当程序中出现了某些"错误”,但该错误信息并没有在Throwable子类中描
述处理,这个时候可以自己设计异常类,用于描述该错误信息。
自定义异常的步骤
- 定义类:自定义异常类名(程序员自己写)继承Exception或RuntimeException
- 如果继承Exception,属于编译异常
- 如果继承RuntimeException,属于运行异常(一般来说, 继承RuntimeException)
try入门-细节-练习
package com.xz.exception_;
/**
* @author 许正
* @version 1.0
*/
public class Exception01 {
public static void main(String[] args) /*throws Exception*/ {
int n1 = 10;
int n2 = 0;
//1.num1/num2=>10/0
//2.当执行到num1 / num2 因为num2 = 0,程序就会出现(抛出)异常ArithmeticException
//3. 当抛出异常后,程序就退出,崩溃了,下面的代码就不在执行
//4.这样的程序并不好,不应该出现了一个不算致命的问题,就导致整个系统崩溃
//5.java设计者,提供了一个叫异常处理机制来解决该问题
// int res = n1 / n2;
//如果程序员,认为段代码可能出现异常/问题,可以使用try-catch异常处理机制来解决
//从而保证程序的健壮性
//将该代码块->选中->快捷键ctrL + alt + t ->选中try-catch
//6. 如果进行异常处理,那么即使出现了异常,程序可以继续执行
try {
int res = n1 / n2;
} catch (Exception e) {
System.out.println("异常出现的原因:" + e.getMessage());
}
System.out.println("程序继续运行...");
}
}
package com.xz.try_;
/**
* @author 许正
* @version 1.0
*/
public class TryCatchDetail {
public static void main(String[] args) {
try {
String str = "Zeaper";
int num = Integer.parseInt(str);
System.out.println(num);
} catch (NumberFormatException e) {
System.out.println("异常信息:" + e.getMessage());
} finally {
System.out.println("finally代码块被执行...");
}
System.out.println("程序继续执行...");
}
}
package com.xz.try_;
/**
* @author 许正
* @version 1.0
*/
public class TryCatchDetail02 {
public static void main(String[] args) {
//1.如果try代码块有可能有多个异常
//2. 可以使用多个catch 分别捕获不同的异常,相应处理
//3.要求子类异常写在前面,父类异常写在后面
try {
Person person = new Person();
person = null;
System.out.println(person.getName());
int n1 = 10;
int n2 = 0;
int res = n1 / n2;
} catch (NullPointerException e) {
System.out.println("空指针异常");
} catch (ArithmeticException e) {
System.out.println("算术异常");
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
}
}
}
class Person {
private String name;
public String getName() {
return name;
}
}
package com.xz.try_;
/**
* @author 许正
* @version 1.0
*/
public class TryCatchDetail03 {
public static void main(String[] args) {
// 可以进行try-finally 配合使用,这种用法相当于没有捕获异常,
// 因此程序会直接崩掉/退出。应用场景,就是执行一段代码,不管是否发生异常,
// 都必须执行某个业务逻辑
try {
int num1 = 10;
int num2 = 0;
int res = num1 / num2;
} finally {
System.out.println("finally代码块被执行...");
}
System.out.println("程序继续执行...");
}
}
package com.xz.try_;
import java.util.Scanner;
/**
* @author 许正
* @version 1.0
*/
public class TryCatchExercise {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = 0;
while (true) {
System.out.println("请输入一个整数:");
String str = scanner.next();
try {
num = Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
System.out.println("您输入的值不是一个整数!!!");
}
}
System.out.println("您输入的数值为: " + num);
}
}
//public class TryCatchExercise {
// public static void main(String[] args) {
// Scanner scanner = new Scanner(System.in);
// int num = 0;
// while (num == 0) {
// System.out.println("请输入一个整数:");
// try {
// int input = scanner.nextInt();
// num = -1;
// } catch (Exception e) {
// System.out.println("您输入的不是一个整数!!!");
// }
// }
// System.out.println("输入正确");
System.out.println("您输入的数值为:" + input);
// }
//}
throw/throws
package com.xz.throws_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
/**
* @author 许正
* @version 1.0
*/
public class Throws01 {
public static void main(String[] args) {
}
public void f2() throws FileNotFoundException, NullPointerException, ArithmeticException {
//创建了一个文件流对象 I
//1.这里的异常是一个FiLeNotFoundException编译异常
//2.使用前面讲过的try- catch- finally
//3. 使用throws, 抛出异常, 让调用f2方法的调用者( 方法)处理
//4. throws后 面的异常类型可以是方法中产生的异常类型,也可以是它的父类
//5. throws 关键字后也可以是异常列表,即可以抛出多个异常
FileInputStream fis = new FileInputStream("d:aa.txt");
}
}
自定义异常
package com.xz.customexception;
/**
* @author 许正
* @version 1.0
*/
public class CustomException {
public static void main(String[] args) {
int age = 90;
//这里我们可以通过构造器,设置信息
if (!(age >= 18 && age <= 80)) {
throw new AgeException("年龄需要在18~80之间!");
}
System.out.println("您的年龄范围正确!");
}
}
//自定义一个异常
//1. 一般情况下,我们自定义异常是继承RuntimeException
//2.即把自定义异常做成运行时异常,好处是,我们可以使用默认的处理机制 比较方便
class AgeException extends RuntimeException {
public AgeException(String message) {
super(message);
}
}
Exercise
package com.xz.homework;
/**
* @author 许正
* @version 1.0
*/
public class Homework01 {
public static void main(String[] args) {
try {
if (args.length != 2) {
throw new ArrayIndexOutOfBoundsException("参数个数不对!");
}
//把接收到的参数转为int
int num1 = Integer.parseInt(args[0]);
int num2 = Integer.parseInt(args[1]);
double res = num1 / num2;
System.out.println("num1/num2 = " + res);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(e.getMessage());
} catch (NumberFormatException e) {
System.out.println("参数格式不正确,需要输入两个整数!");
} catch (ArithmeticException e) {
System.out.println("出现了除以0的异常!");
}
}
}