异常概念 异常体系
图片.png
异常的产生过程解析
异常的产生过程解析
throw关键字
throw关键字
Objects非空判断
public static void main(String[] args) {
test(null);
}
public static void test(Object object){
Objects.requireNonNull(object, "object 方法为null");
}
Objects非空判断
throws关键字
public static void main(String[] args) throws FileNotFoundException {
test("c:\\a.txt111");
}
public static void test(String filrName) throws FileNotFoundException{
if (!filrName.equals("c:\\a.txt")){
throw new FileNotFoundException("文件没找到");
}
}
throws关键字
try...catch关键字
public static void main(String[] args) {
try {
test("c:\\a.txt111");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("出现异常");
}
}
public static void test(String filrName) throws FileNotFoundException{
if (!filrName.equals("c:\\a.txt")){
throw new FileNotFoundException("文件没找到");
}
}
try...catch关键字
Throwable处理异常的三个方法
public static void main(String[] args) {
try {
test("c:\\a.txt111");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
}
public static void test(String filrName) throws FileNotFoundException{
if (!filrName.equals("c:\\a.txt")){
throw new FileNotFoundException("文件没找到");
}
}
![Throwable处理异常的三个方法(https://upload-images.jianshu.io/upload_images/16609281-229269a397216b69.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
finally 代码块
public static void main(String[] args) {
try {
test("c:\\a.txt111");
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
System.out.println(e.toString());
e.printStackTrace();
}
finally {
System.out.println("肯定执行");
}
}
public static void test(String filrName) throws FileNotFoundException{
if (!filrName.equals("c:\\a.txt")){
throw new FileNotFoundException("文件没找到");
}
}
图片.png
注意事项:finally里面有return语句
子父类异常
子父类异常
自定义异常
package com.mujiachao;
public class RegisterExcetion extends Exception{
public RegisterExcetion() {
}
public RegisterExcetion(String message) {
super(message);
}
}
···
public static void main(String[] args) {
test();
}
public static void test(){
String[] username={"张三","李四","王五"};
System.out.println("请输入要注册的用户名:");
Scanner scanner = new Scanner(System.in);
String next = scanner.next();
for (String s : username) {
if (s.equals(next)){
try {
throw new RegisterExcetion("用户名已存在");
} catch (RegisterExcetion registerExcetion) {
registerExcetion.printStackTrace();
return;
}
}
}
System.out.println("恭喜注册成功");
}
···
自定义异常