概述
异常体系结构:
java.lang.Throwable
Error:JVM无法解决的严重问题,如堆溢出、栈溢出等,只能考虑修改代码。
public static void main(String[] args){
//栈内存溢出
main(args)
//堆内存溢出
Integer[] arr=new Integer[1024*1024*1024]
}
Exception:程序编译、运行时出现的异常。
总之,异常的处理是针对Exception的
=========================================================================
Java异常的处理机制
方式一 try-catch-finally
try{
}catch(异常类型1 变量名1){
}catch(异常类型2 变量名2){
}catch(异常类型3 变量名3){
}catch(异常类型4 变量名4){
}finally{
//一定会执行的代码(可选的)
// return 语句执行前,需要先执行finally
}
catch可打印 e.getMessage() 打印异常数据
e.printStackTrace() 打印堆栈信息
方式一可以嵌套
方式二 throws+异常类型
throws+ 异常类型写在方法声明处,方法被使用时如有异常会向上抛异常,异常并未本处理
最终通过调用者执行try-catch-finally抛出异常
public void test() throws IOException {
}
方式一和方式二具体使用场景
在父类中被重写的方法没有throws抛出异常,子类重写的方法也不能throws异常
子类中出现异常用try-catch-finally去解决
被调用的方法如有异常最好用throws向上抛出异常,最后用try-catch-finally做统一处理
=========================================================================
异常处理的三种方式
自动异常处理:上面方式一、二
手动异常处理:throw new RunTimeException();
Exception();
public class ExceptionTest01 {
public static void main(String[] args) {
User student1=new User();
try {
student1.login(-1);
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
class User{
private int id;
public void login(int id) throws Exception {
if (id>0){
this.id=id;
}
throw new Exception("输入数据非法");
}
}
控制台输出
用户自定义异常
类继承RunTimeException或者Exception
public class CustomExceptionTest {
public static void main(String[] args) {
char a = 'a';
int b = 97;
try {
if (a == b) {
throw new UserException(a, b);
}
} catch (UserException ue) {
System.out.println(ue);;
}
}
}
class UserException extends RuntimeException {
char name;
int password;
public UserException(char name, int password) {
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "UserException{" +
"name=" + name +
", password=" + password +
'}';
}
}
控制台输出