异常
异常的根类是java.lang.Throwable
,其包括Error
和Exception
两个子类。Error
我们不能解决,如内存溢出等。但是Exception
可以避免(编译异常、运行时异常等)。
try、catch、finally、throw、throws
throw抛出异常
应用于方法内,如:用if语句判断是否超过索引,如果是就抛出异常:
throw new ArrayIndexOutOfBoundsException("数组越界");
public class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int index = 10;
if (index >= 4) {
throw new ArrayIndexOutOfBoundsException("数组越界");
} else {
System.out.println(arr[index]);
}
}
}
throws声明异常
应用于方法之上,格式:public void method() throws XxxException {}
- 如果方法内部有抛出异常,throws后面必须声明。
- 声明了异常,要么继续抛给方法的调用者,要么交给
tray{}catch
public class Test {
public static void main(String[] args) throws ArrayIndexOutOfBoundsException{
int[] arr = {1, 2, 3, 4};
int index = 10;
if (index >= 4) {
throw new ArrayIndexOutOfBoundsException("数组越界");
} else {
System.out.println(arr[index]);
}
}
}
try..catch捕获异常
如果不throws异常,那么可以捕获异常,自己处理。一般在工作中,会把异常信息记录在日志。
- catch可以有多个,不能重复,子异常先与父异常处理。
public class Test {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4};
int index = 10;
try {
System.out.println(arr[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界");
System.out.println(e.getMessage()); // 简短描述
System.out.println(e.toString()); // 详细描述
e.printStackTrace(); // 最全面信息
}
System.out.println("后续代码也会运行");
}
}
子类继承父类时,对抛出异常的处理:
- 父类有抛出异常,子类可以抛出相同的异常,或者抛出子异常,或者不抛出;
- 父类没有抛出异常,子类也可以抛出,但必须捕获。
自定义异常类
需要继承两个类:
java.lang.Exception
编译异常,要么trows,要么try{}catchjava.lang.RuntimeException
运行异常,交给虚拟机处理
例子:模拟注册,如果用户存在,则抛出异常
import java.util.*;
public class Test {
static String[] usernames = {"张三", "李四", "王五"};
public static void main(String[] args) {
System.out.println("请输入您要注册的用户名: ");
Scanner sc = new Scanner(System.in);
String username = sc.next();
check(username);
}
public static void check(String username) {
for (String name : usernames) {
if (name.equals(username)) {
try {
throw new MyException("用户名已注册!!!");
} catch (MyException e) {
e.printStackTrace();
return; // 结束
}
}
}
System.out.println("恭喜您,注册成功!");
}
}
class MyException extends Exception {
public MyException() {
}
public MyException(String message) {
super(message);
}
}