1.异常的处理方案
1)异常抛出: throws 把异常抛出到上一层,谁调用谁解决
2)异常捕获: try … catch
try{
有可能出现异常的代码;
}catch(FileNotFoundException e){
处理异常代码;
}catch(NullPointerException e){
处理异常代码;
}catch(Exception e){
所有异常都能接收;
}finally{
无论try中是否会出现异常,都会执行finally中的代码
//资源的关闭等代码
}
注意:
1.一个try的后面可以接1~n个catch
2.try中如果出现异常,try下面的代码不会执行,直接进入catch的判断
3.catch从上到下一次判断,满足哪一个catch捕获的类型,就执行对应的语句体
4.异常一旦捕获,程序执行过程中出现的异常按照指定方案解决,不会影响后续代码
public class Class02_Exception {
public static void main(String[] args) {
System.out.println("主方法开始了");
//异常捕获
try{
System.out.println("try开始了");
test();
}catch (FileNotFoundException e){
System.out.println("这是文件未找到异常");
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}finally {
System.out.println("最终的代码无论是否出现异常都会执行");
}
System.out.println("主方法结束了");
}
2.自定义异常
1)类型:自定义的异常类型
2)使用:
1.所有自定异常类型必须直接或间接继承自Exception
2.如果自定义异常为运行时异常,需要直接或间接的继承自RuntimeException
3.throws 制造异常
3)例题
public class Class03_DefineException {
public static void main(String[] args) {
User user = new User();
user.setUsername("zhangsan");
int age = 8;
try{
user.setAge(28);
}catch (AgeException e){
try{
user.setAge(18);
}catch (AgeException ageException){
ageException.printStackTrace();
}
}
System.out.println(user);
}
}
class AgeException extends Exception{
public AgeException(){}
public AgeException(String message) {
super(message);
}
}
class User{
private String username;
private int age;
public User(){
}
public User(String username, int age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException{
if (age<18 || age>100){
throw new AgeException(age+"不合法");
}
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}