1. 继承源
:java有大量的异常类,继承自java.lang.Throwable类。
2.体系架构图
- arithmetic:算数
-
- Error称为错误类,是系统内部错误或资源耗尽的错误,是比较严重的。
-
- Exception是异常类,其中RuntimeException及其子类属于运行时异常,其他子类为编译时异常。
-
- Throwable的常用方法
方法声明 | 功能 |
---|---|
String getMessage() | 返回此throwable的详细信息字符串 |
void printStackTrace() | 将此throwable及其追踪输出至标准错误流 |
void printStackTrace(PrintStream s) | 将此throeable及其追踪返回至指定输出流 |
3. 异常捕获 :try…catch和 finally
try{
//代码块
}catch(ExceptionType(Exception类及其子类) e){ //指定一个参数指明他所能够接收异常的类型
//对Exeption的处理
}
public class Example21 {
public static void main(String[] args) {
try {
int result = divite(4,0);
System.out.println(result);
}catch(Exception e) {
System.out.println(e.getMessage());
System.out.println("程序继续向下运行");
}
}
public static int divite(int x,int y) {
int result = x/y;
return result;
}
}
- 注意:程序铺捉到try中的异常时转向执行catch的代码,代码不会因此终止,继续运行。
- try中捕捉到异常后不会执行后面的语句,如
System.out.println(result);
,如果强制执行,可以在代码最后加 finally{}
}catch(Exception e) {
System.out.println(e.getMessage());
return;
}finally {
System.out.println("进入finally 代码块");
}
System.out.println("程序继续向下运行");
}
- 在catch中return结束了语句的执行,后面的sys不会再执行,但是finally仍然执行。经常用来完成必须完成的,如释放资源
- 当在try…catch中执行了System.exit(0)语句,表示退出当前java虚拟机。此时任何代码都不会执行了,包括finally
4. throw关键字抛出异常
修饰符 返回值类型 方法名([参数1,参数2...])throws Exception1[Exception Type2...]{
}
- throws用在方法声明后面,通常称为 方法声明抛出一个异常
package yichang;
public class Exception22 {
public static void main(String[] args) {
try {
int result = divite(4,2);
System.out.println(result);
}catch(Exception e) {
e.printStackTrace();
}
}
public static int divite(int x,int y) throws Exception {
int result = x/y;
return result;
}
}
- 注意:因为方法声明抛出了异常,所以在主方法中,需要对代码已经异常捕获处理,否则就会发生编译错误。
- 如果不知道如何处理声明抛出的异常(try…catch)可以继续抛出异常,此时如果发生异常,没有被处理,程序将自动停止
public class Exception22 {
public static void main(String[] args)throws Exception {
int result = divite(4,0);
System.out.println(result);
}
public static int divite(int x,int y) throws Exception {
int result = x/y;
return result;
}
}
5. 运行时异常与编译时异常
- 编译时异常:通常称为checked异常,编辑器通常会对其进行检查,如果出现异常必须进行处理
- 1使用try…catch语句对异常进行捕获
- 2使用throws关键字声明抛出异常
- 运行时异常,通常称为unchecked异常,编辑器不会对其进行检查,一般是由逻辑错误引起的,即使没有try…catch和throws抛出处理,也可能可以运行,如
int[] arr=new int[5];
System.out.print(arr[6]);
- 角标的越界
6.自定义异常
- 必须继承Exception或其子类。
自定义异常类,没有特殊情况,只需要继承Exception类即可
public class DivideBy extends Exception{
public DivideBy() {
super();
}
public DivideBy(String message) {
super(message);
}
}
- 用throw关键字抛出异常的实例对象
public class Exception23 {
public static void main(String[] args) {
try {
int result = divite(4,-2);
System.out.println(result);
}catch(DivideBy e){
System.out.println(e.getMessage());
}
}
public static int divite(int x,int y) throws DivideBy {
if(y<0) {
throw new DivideBy("除数是负数");
}
int result=x/y;
return result;
}
}