一、异常的类型
1、运行时异常//extends RuntimeException
2、编译异常//必须自己处理
常见的异常:
①空指针异常 NullPointerException
public static void main(String[] args) {
String str = null;
//此处报空指针异常
System.out.println(str.length());
}
控制台输出:
Exception in thread "main" java.lang.NullPointerException
at cn.com.gjw.MyClass.main(MyClass.java:7)
②数组下标越界异常 ArrayIndexOutOfBoundsException
public static void main(String[] args) {
int arr[] = {1,2};
// 此处报数组下标越界异常
System.out.println(arr[2]);
}
控制台输出的异常信息为:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at cn.com.gjw.MyClass.main(MyClass.java:7)
③算数异常 ArithmeticException
public static void main(String[] args) {
// 整数0做了分母,报算术运算异常
System.out.println(1 / 0);
}
控制台输出的异常信息为:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at cn.com.gjw.MyClass.main(MyClass.java:6)
二、异常的处理方式
1、jvm 虚拟机处理
运行java程序的抽象计算机
异常名称 异常信息 异常出现的位置 打印到控制台
2、自己处理
①:try catch finally
try{
//可能出现异常的代码
int i = 2/0;
System.out.println("11111");//不会出现
}catch(Exception e){
System.out.println("除数不能为0");
}catch(异常类型1 异常的变量名1){
}catch(异常类型2 异常的变量名2){
}finally{
System.out.println("2222");//会出现
}
②:抛出异常 throws (在方法后面抛出)
public static void main(String[] args) {
div(a:1,b:0);
}
void static div (int a,int b){
int c = a/b;
return c;
}
三、编写异常
例:
①:创建三个类
②:在Text01内写入如下代码
public class Text01 {
public static void main(String[] args) {
Person person = new Person();
try {
person.setAge(-1);
} catch (AgeException e) {
e.printStackTrace();
}
}
}
用try catch处理异常,当出现自己定义的AgeException异常时,输出字符
调用person
③:在Person编写如下代码
public class Person {
int age;
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if(age>=1 && age<150){
this.age = age;}
else {
throw new AgeException("该年龄不属于人类");
}
}
}
判断年龄是否属于定义的年龄段内
④:编写AgeException异常
public class AgeException extends Exception{
public AgeException(String message) {
super(message);
}
}
继承总异常 AgeException extends Exception
在出现异常时,输出字符
⑤:运行结果