| 常见 | 理解 |
|---|---|
| Throwable | 异常父类 |
| Exception | 可修复异常 |
| Error | 系统级别错误:内存不足哦 |
| … | … |
| 方式 | 名称 |
|---|---|
| try{} catch(); | 捕获异常 |
| throws | 抛出异常 |
| throw | 自定义异常 |
1.运行期异常
// 将有异常的代码使用try{} catch();进行捕获异常
try{
num=num/0;
}catch (ArithmeticException e){
System.out.println("捕获到的异常信息"+e.getMessage());
}
2.编译期异常
// 使用 throws 抛出异常 谁调用谁处理异常
public static void loadUserInfo() throws FileNotFoundException {
FileOutputStream fos=new FileOutputStream("./src/test.txt");
}
// 或者
try {
FileOutputStream fos=new FileOutputStream("./src/test.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
3.自定义异常继承Exception
public class LoginException extends Exception{
// 重写Exception
}
Scanner scanner=new Scanner(System.in);
System.out.println("请输入用户名");
String username=scanner.next();
System.out.println("请输入密码");
String password=scanner.next();
if(!"ldk".equals(username) && "123".equals(password)){
throw new LoginException("用户名或者密码错误");
}else {
System.out.println("登录成功");
}
}
3.finally的作用
finally语句为异常处理提供一个统一的出口,使得在控制流程转到程序其它部分以前,能够对程序的状态作统一管理
无论try所指定的程序块中是否抛出异常,finally所指定的代码都要被执行
通常在finally语句中可以进行资源的释放工作,如关闭打开的文件、删除临时文件等。
finally {
// 无论是否发生异常,都会被执行
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}



