Java学习(8) —— 异常处理

常见异常分类:

import java.io.File;
import java.io.FileInputStream;

public class Test{
    public static void main(String[] args) {
        //FileNotFoundException
        File file = new File("test.txt");
        FileInputStream f = new FileInputStream(file);
        int i = f.read();
        f.close();
    }
}
import java.util.Date;
import java.util.Scanner;

public class Test{
    public static void main(String[] args) {
        //NullPointerException(空指针异常)
        String str = null;
        System.out.println(str.charAt(0));
        
        //ClassCastException(类型转换异常)
        Object obj = new Date();
        String str3 = (String)obj;

        //NumberFormatException(数值转换异常)
        String str4 = "ab";
        int i1 = Integer.parseInt(str4);

        //InputMismatchException(输入不匹配)
        Scanner scanner = new Scanner(System.in);
        int i2 = scanner.nextInt();
        System.out.println(i2); //如果输入的不是数字,则异常

        //ArithmeticException(算数异常)
        int a = 2;
        int b = 0;
        System.out.println(a / b);

        //ArrayIndexOutOfBoundsException(数组角标越界)
        int[] arr = new int[3];
        System.out.println(arr[3]);
        //StringIndexOutOfBoundsException(字符串角标越界)
        String str2 = "abc";
        System.out.println(str.charAt(3));
    }
}

程序在执行过程中,一旦出现异常,系统就会在异常代码处生成一个对应异常类的对象,并将此对象抛出。一旦抛出对象以后,后面的代码就不再执行。

处理异常的方式:(1)try-catch-finally;(2)throws

一.   try-catch-finally

        try{

                可能出现异常的代码

        }catch(异常类型1  变量名1){

                处理异常的方式1

        }catch(异常类型2  变量名2){

                处理异常的方式2

        } . . .

          . . .

         finally{

                 一定会执行的代码

         }

IDEA快捷键:CTRL+ALT+T  (鼠标选中准备进行try-catch-finally的区域,然后使用快捷键)

(1)finally是可选的。

(2)使用try将可能出现异常的代码包装起来,在执行过程中,一旦出现异常,就会生成一个对应异常类的对象,根据此对象的类型,去catch中进行匹配。

(3)一旦try中的异常对象匹配到某一个catch时,就进入到catch中进行异常处理。一旦处理完成,就跳出当前的try-catch结构,继续执行后面的代码。

(4)catch中的异常类型如果有子父类关系,则要求子类一定声明在父类的上面,否则会报错。

(5)异常处理的常用方式:getMessage()、printStackTrace()

(6)try结构中定义的变量,在try结构外不能被调用。

(7)try-catch-finally在处理编译时异常时,使程序在编译时不报错,但是执行时仍可能报错。

public class Test{
    public static void main(String[] args) {
        //NumberFormatException
        String str = "ab";
        try{
            int i1 = Integer.parseInt(str);
        }catch(NumberFormatException e){
            System.out.println("出现数值转换异常");
            System.out.println(e.getMessage());
            //e.printStackTrace();
        }catch(NullPointerException e){
            System.out.println("出现空指针异常");
        }catch(Exception e){
            System.out.println("出现异常");
        }

        System.out.println("end");

        //输出:出现数值转换异常
        //     For input string: "ab"
        //     end
    }
}

(8)finally中声明的是一定会被执行的代码,即使catch中又出现了异常、try中有return语句或catch中有return语句等情况。

public class Test{
    public static void main(String[] args) {
        //NumberFormatException
        String str = "ab";
        try{
            int i1 = Integer.parseInt(str);
        }catch(NumberFormatException e){
            System.out.println("出现数值转换异常");
            int[] arr = new int[3];
            System.out.println(arr[3]);
        }catch(NullPointerException e){
            System.out.println("出现空指针异常");
        }catch(Exception e){
            System.out.println("出现异常");
        }finally{
            System.out.println("一定会执行");
        }

        System.out.println("end");
        
        //输出:出现数值转换异常
        //     一定会执行
    }
}

 (9)像数据库连接、输入输出流、网络变成Socket等资源,JVM不能自动回收,我们需要手动进行资源释放,此时的资源释放需要声明在finally中。

(10)try-catch可以嵌套使用

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class Test{
    public static void main(String[] args) {
        //FileNotFoundException
        FileInputStream f = null;
        try{
            File file = new File("test.txt");
            f = new FileInputStream(file);
            int i = f.read();
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(f != null){
                    f.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

二.    throws + 异常类型

         “ throws + 异常类型 ”写在方法的声明处,指明执行此方法时可能会出现的异常类型,一旦方法体执行时出现异常,会在异常代码处生成一个异常类对象,此对象满足throws后的异常类型时,就会被抛出,后面的代码不会继续执行。

IDEA快捷键:ALT+ENTER (光标移到标红线处,然后使用快捷键)

           try-catch-finally:真正把异常解决了;throws:将异常抛给方法的调用者,并没有真正处理异常。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Test{
    public static void main(String[] args) {
        try{
            test2();               //不能继续往上抛,必须使用try-catch解决
        }catch (IOException e){
            e.printStackTrace();
        }

        test3();  //不会报错
    }

    public static void test3(){
        try{
            test1();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void test2() throws IOException{
        test1();
    }

    public static void test1() throws IOException{
        //FileNotFoundException
        File file = new File("test.txt");
        FileInputStream f = new FileInputStream(file);
        int i = f.read();
        f.close();
    }
}

           子类重写的方法抛出的异常不大于父类被重写的方法抛出的异常

            父类中被重写的方法没有用throws抛异常,则子类重写的方法也不能用throws抛异常,如果有异常,只能使用try-catch-finally方式处理。

import java.io.FileNotFoundException;
import java.io.IOException;

public class Test{
    public static void main(String[] args) {
    }

}

class SuperClass{
    public void test1() throws IOException{

    }
}

class SubClass extends SuperClass{
    public void test2() throws FileNotFoundException{

    }

}

三.   手动生成异常,并抛出(throw)

public class Test{
    public static void main(String[] args) {
        try{
            Person person = new Person();
            person.show(-2);
            System.out.println(person.age);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        //输出:输入数据错误
    }

}

class Person{
    int age;

    public void show(int age) throws Exception{   //处理异常
        if(age > 0){
            this.age = age;
        }else{
            throw new Exception("输入数据错误");     //手动抛出异常对象
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值