异常类,异常处理、常见的异常类

异常类,异常处理、常见的异常类

异常类,异常处理

java将错误封装为类,不是一个类,而是一组类,这些类也是有层级关系的

最顶端的是Throwable,是根节点

Throwable 有两个直接子类:Error 和 Exception

Error:AWTError、IOError、OutOfMemoryError

Exception:IOException、RuntimeException

常见的异常类:

ArithmeticException:表示数学运算异常(1/0)

System.out.println(1/0);

0不能为除数

ClassNotFoundException:表示类未定义异常(常用于反射创建对象)

public class Person {

public void method(Integer num){

System.out.println(num);

}

}

Class personClazz = Class.forName("com.deepSeek.shuwu.Day5.Person1");

我们找不到这个包下面的Person1对象,爆出ClassNotFoundException异常

IllegalArgumentException:表示参数格式错误异常(常用于反射调用对象的方法)

public class Person {

public void method(Integer num){

System.out.println(num);

}

}

Class personClazz = Class.forName("com.deepSeek.shuwu.Day5.Person");

personClazz.getMethod("method",Integer.class).invoke(new Person(),"dwda");

可以看见method方法是需要的Interger参数,而我们传递的是字符串

ArrayIndexOutOfBoundsException:数组下标越界异常(常出现在数组取值)

int[] arr ={1,2,3};

System.out.println(arr[3]);

arr[]数组下标最大为2,所以爆出数字下标越界异常

NullPointerException:空指针异常

public class Person {

public void method(Integer num){

System.out.println(num);

}

}

Person person =null;

person.method(1);

我们调用的对象未创建,所以无法调用这个对象的方法

NoSuchMethodException:方法未定义异常

public class Person {

public void method(Integer num){

System.out.println(num);

}

}

Class personClazz = Class.forName("com.deepSeek.shuwu.Day5.Person");

personClazz.getMethod("method1",Integer.class).invoke(new Person(),1);

Person类未定义method1方法,所以爆出NoSuchMethodException异常

NumberFormatException:数值类型转换异常

String str = "123a";

int num = Integer.parseInt(str);

System.out.println(num);

123a字符串无法转化为Integer类型

throw和throws

都是java在处理异常使用的关键字

throw:主动抛出一个异常对象throws:声明这个方法或者类可能会抛出异常,给开发者使用的时候提醒他捕获异常

在test()方法声明的个throws Exception方法,那么这个方法就可能会抛出异常,在调用的时候如果不写try-catch方法就会爆红

自定义异常

实际开发中,除了java提供的异常类还可以自定义异常

如何使用自定义异常

自定义异常类:

public class MyNumException extends Exception {

public MyNumException(String error) {

super(error);

}

}

测试:

public class Test {

public static void main(String[] args){

Test test = new Test();

try {

System.out.println(test.test("String"));

} catch (MyNumException e) {

e.printStackTrace();

}

}

public Integer test(Object object) throws MyNumException{

if(!(object instanceof Integer)){

throw new MyNumException("传入参数不是整数类型");

}else {

Integer num = (Integer) object;

return num;

}

}

}

结果 :