异常
异常的概述
什么是异常?
异常就是Java程序在运行过程中出现的错误异常的由来
问题也是显示生活中一个具体事务,也可以通过Java类的形式进行描述。并封装成对象,其实就是 Java对不正常情况进行描述后的对象体现。
例如:
医院的病种
- 常见的异常
角标越界异常、空指针异常、 lass ast xception
异常的继承体系
在 Java 中使用 Exception 类来描述异常。 Exception 类及其子类是 Throwable 的一种形式,它用来表示 Java程序中可能会产生的异常,并要求对产生的异常进行合理的异常处理。 Exception 有继承关系,它的父类是 Throwable。 Throwable 是 Java 语言中所有错误或异常的超类。
异常与错误的区别
异常:指程序在编译、运行期间发生了某种异常(XxxException),我们可以对异常进行具体的处理。不处理异常,程序将会结束运行。
错误:指程序在运行期间发生了某种错误(XxxError),Error错误通常没有具体的处理方式,程序将会结束运行。Error错误的发生往往都是系统级别的问题,都是jvm所在系统发生的,并反馈给jvm的。我们无法针对处理,只能修正代码。
总结:异常可在代码中提前处理,即执行预处理代码,而错误需要重新考虑代码正确逻辑关系,修改代码
异常声明、抛出以及处理
抛出异常throw
在编写程序时,我们必须要考虑程序出现问题的情况。比如,在定义方法时,方法需要接收参数。那么,当使用接收到的参数时,首先要对参数进行合法的判断,参数若不合法,就应该告诉调用者,传递合法的数据进来。这时可以使用抛出异常的方式来告诉调用者。
在 Java 中,提供了一个 throw 关键字,它用来抛出一个指定的异常对象。
如何使用?
1. 创建一个异常对象。封装一些提示信息(信息可以自己编写)。
2. 需要将这个异常对象告知给调用者。怎么将这个异常对象传递到调用者处呢?
可以通过关键字throw就可以完成。
throw 用在方法内,用来抛出一个异常对象,将这个异常对象传递到调用者,并结束当前方法的执行。
使用格式
throw new 异常类名(参数);
代码示例
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1,2,3,4};
int i = getElement(arr, 7);
System.out.println(i);
}
// 通过给定的数组,返回给定的索引对应的元素值。
public static int getElement(int[] arr,int index){
if(arr == null){
throw new NullPointerException("亲,你的数组是空的");
}
if(arr.length <= index ||index < 0){
throw new ArrayIndexOutOfBoundsException("亲,索引越界了");
}
return arr[index];
}
}
声明异常throws
声明:将问题标识出来,报告给调用者。如果方法内通过 throw 抛出了编译时异常,而 没有捕获处理(稍后讲解该方式),那么必须通过 throws 进行声明,让调用者去处理。
声明异常格式:
修饰符 返回值类型 方法名(参数) throws 异常类名1,异常类名2… { }
代码示例
// 如果定义功能时有问题发生需要报告给调用者。可以通过在方法上使用throws 关键字进行声明。
public static void chose(int x) throws Exception {
if (x > 0) {
throw new Exception();
} else {
System.out.println("show run");
}
}
throws 用于进行异常类的声明,若该方法可能有多种异常情况产生,那么在 throws 后 面可以写多个异常类,用逗号隔开。
代码示例
public static int getElement(int[] arr,int index) throws NullPointerException,ArrayIndexOutOfBoundsException{
if(arr == null){
throw new NullPointerException("亲,你的数组是空的");
}
if(arr.length <= index ||index < 0){
throw new ArrayIndexOutOfBoundsException("亲,索引越界了");
}
return arr[index];
}
捕获异常
单 catch
try:该代码块中编写可能产生异常的代码。
catch:用来进行某种异常的捕获,实现对捕获到的异常进行处理。
捕获:Java 中对异常有针对性的语句进行捕获,可以对出现的异常进行指定方式的处理
语法格式
try{
//可能出现异常的代码
}catch(异常类型 变量名){
//异常类型:是 try 中代码可能出现的异常类型
//如果 try 中代码出现异常,将跳到此处执行;
}
代码示例
public class Test03 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4 };
try {
System.out.println(arr[4]);
System.out.println("aaa");
System.out.println("bbb");
} catch (ArrayIndexOutOfBoundsException e) {
//System.out.println(e.getMessage());
System.out.println("s数组索引越界异常");
}
System.out.println("程序运行结束");
}
}
多catch
try{
//多行代码,可能产生多种异常
}catch(异常类型1 变量名){
...
}catch(异常类型2 变量名){
...
}catch(异常类型n 变量名){
...
}
代码示例
public class Test04 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4 };
int[] w1 = null;
try {
System.out.println(w1[1]);
System.out.println("aaa");
System.out.println("bbb");
} catch (ArrayIndexOutOfBoundsException e) {
//System.out.println(e.getMessage());
System.out.println("s数组索引越界异常");
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("该数组是空数组");
}
System.out.println("程序运行结束");
}
}
try…catch…finally
捕获异常格式:
try{
//可能出现异常的代码
}catch(异常类型 变量名){
//异常类型:是 try 中代码可能出现的异常类型
//如果 try 中代码出现异常,将跳到此处执行;
}finally{
一定会执行的代码
}
finally:有一些特定的代码无论异常是否发生,都需要执行。另外,因为异常会引发 程序跳转,导致有些语句执行不到。而 finally 就是解决这个问题的,在 finally 代码块中存放 的代码都是一定会被执行的。
示例代码
public class Test05 {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4 };
int[] w1 = null;
try {
System.out.println(w1[1]);
System.out.println("aaa");
System.out.println("bbb");
} catch (ArrayIndexOutOfBoundsException e) {
//System.out.println(e.getMessage());
System.out.println("s数组索引越界异常");
} catch (NullPointerException e) {
// TODO: handle exception
System.out.println("该数组是空数组");
}finally {
System.out.println("这句话一定会说出来");
}
}
}
多 catch异常处理方式
- try catch finally 组合:检测异常,并传递给 catch 处理,并在 finally 中进行 资源释放。
- 一个 try 多个 catch 组合:对代码进行异常检测,并对检测的异常传递给 catch 处理。对每种异常信息进行不同的捕获处理。
注意:这种异常处理方式,要求多个 catch 中的异常不能相同,并且若 catch 中的多个异 常之间有子父类异常的关系,那么子类异常要求在父类异常最上面。
JDK7 多个异常处理方式
语法
try{
//代码可能出现多种异常
}catch(异常类型 1| 异常类型 2| 异常类型 3e){
//几种异常的统一的处理方式
}
注意
- catch 中的多个异常类型是”或”的关系,不能出现”父类异常类型”
- 可以使用多个 catch 语句
示例代码
public class Demo {
public static void main(String[] args) {
int a = 10;
int b = 2;
int[] array1 = new int[2];
String[] strArray = { "a", "b" };
try {
System.out.println(a / b);
System.out.println(array1.length);
System.out.println(strArray[2]);
// 其它代码
} catch (ArithmeticException | NullPointerException | ArrayIndexOutOfBoundsException e) {
if (e instanceof ArithmeticException) {
}
if (e instanceof NullPointerException) {
}
if (e instanceof ArrayIndexOutOfBoundsException) {
}
} catch (Exception e) {
}
System.out.println("程序结束!");
}
}
注意:异常的处理,指处理异常的一种可能性,即有了异常处理的代码,不一定会产生异常。 如果没有产生异常,则代码正常执行,如果产生了异常,则中断当前执行代码,执行异常处 理代码。
运行时异常
RuntimeException 和他的所有子类异常,都属于运行时期异常。NullPointerException,ArrayIndexOutOfBoundsException 等都属于运行时期异常.
运行时期异常的特点:
-方法中抛出运行时期异常,方法定义中无需 throws 声明,调用者也无需处理此异常
- 运行时期异常一旦发生,需要程序人员修改源代码.class ExceptionDemo{ public static void main(String[] args){ method(); } public static void method(){ throw new RuntimeException(); } }
父子类关系中的异常
子类覆盖父类方法时, 如果父类的方法声明异常, 子类只能声明父类异常或者该异常的子类,或者不声明。
示例代码
public class Fu {
public void method() throws RuntimeException {
}
}
class Zi extends Fu{
public void method() throws RuntimeException {
}
// 抛出父类一样的异常
// public void method() throws NullPointerException{ }
}
当被覆盖的方法没有异常声明时,子类覆盖时无法声明异常的。
Throwable 类常用方法
在 Throwable 类中为我们提供了很多操作异常对象的方法,常用的如下:
String getMessage() 返回此throwable的详细消息字符串
String toString() 返回此throwable的简短描述
void printStackTrace() 将此throwable及其追踪输出至标准错误流
getMessage 方法:返回该异常的详细信息字符串,即异常提示信息
toString 方法:返回该异常的名称与详细信息字符串
printStackTrace:在控制台输出该异常的名称与详细信息字符串、异常出现的代码位置
示例代码
class Demo {
public static void main(String[] args) {
try {
String s = null;
System.out.println(s.length());
} catch (NullPointerException e) {
String message = e.getMessage();
System.out.println(message);
String result = e.toString();
System.out.println(result);
e.printStackTrace();
}
}
}
自定义异常
在上述代码中,发现这些异常都是 JDK 内部定义好的,并且这些异常不好找。书写时也 很不方便,那么能不能自己定义异常呢?
Java 通过类来描述异常。并将问题封装成对象,有些时候,我们需要根据特定的”业务 逻辑”,定义特定的”异常类”,表示跟我们业务相关的一些异常
自定义异常类
NullPointerException 异常类源代码:
示例代码
class NullPointerException extends RuntimeException {
public NullPointerException() {
super();// 调用父类构造方法
}
public NullPointerException(String s) {
super(s);// 调用父类具有异常信息的构造方法
}
}
仿照 NullPointerException 类,自定义编写一个自定义的 RuntimeException
Class 异常名 extends Exception{ // 或继承 RuntimeException
public 异常名(){
}
public 异常名(String s){
super(s);
}
}
示例代码
class MyException extends Exception {
/*
* 为什么要定义构造函数,因为看到 Java 中的异常描述类中有提供对异常对象的初始化方法。
*/
public MyException() {
super();
}
public MyException(String message) {
super(message);// 如果自定义异常需要异常信息,可以通过调用父类的带有字符串参数的构造函数即可。
}
}
自定义异常的练习
//异常类
class AgeException extends Exception {
public AgeException() {
// TODO Auto-generated constructor stub
super();
}
public AgeException(String message) {
// TODO Auto-generated constructor stub
super(message);
}
}
//对象类
public class Person {
private String name ;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Person(String name, int age) throws AgeException{
this.name = name;
if(age >200 || age<0){
throw new AgeException("年龄真的不正常");
}
this.age = age;
}
}
//测试类
public class TestPerson {
public static void main(String[] args) throws AgeException {
// TODO Auto-generated method stub
System.out.println(new Person("guo", 18).getAge());
System.out.println(new Person("guo", -13).getAge());
}
}
造函数到底抛出这个 AgeException 是继承 Exception 呢?还是继承 RuntimeException 呢?
- 继承 Exception,必须要 throws 声明,一声明就告知调用者进行捕获,一旦问题 处理了调用者的程序会继续执行。
- 继承 RuntimeExcpetion,不需要 throws 声明的,这时调用是不需要编写捕获代码 的,因为调用根本就不知道有问题。一旦发生 AgeException,调用者程序会停掉, 并有 jvm 将信息显示到屏幕,让调用者看到问题,修正代码。
异常的几种写法
/*
* 异常处理的几种语法形式:
*
* 1.try...catch...
* 2.try...catch...catch...catch...
* 3.try...catch...finally...
* 4.try...catch...catch...catch...finally...
* 5.try...finally...
*/
public class Test07 {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
System.out.println(a / b);
} catch (Exception e) {
// 1.如果由于用户的数据或者操作引起的,给用户一些提示
// 2.如果是由代码逻辑引起的,就写入日志,后期供程序员修改代码;
// 3.如果程序没发布,这里可以向控制台打印错误信息,用于调试程序;
}
}
}