栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

P375 try-catch-finally的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

P375 try-catch-finally的使用


异常处理方式

[

try-catch-finally的使用

ExceptionTest1类

public class ExceptionTest1 {
    @Test
    public void test1(){
        String str="123";
        str="abc";
        int num=0;
        try {
            //int num = Integer.parseInt(str);//抛出对象,不再执行下一行代码
            num = Integer.parseInt(str);
            System.out.println("hello---1");
        }catch (NullPointerException e){//异常类型必须对应上,此时不会执行里面的代码
            System.out.println("出现空指针异常,不要着急");

        }catch (NumberFormatException e){//异常类型对应上了,会执行
            //System.out.println("出现数值转换异常,不要着急");
            //String getMessage();
            //System.out.println(e.getMessage());//提示输入的是字符串abc不合适
            //printStackTrace()
            e.printStackTrace();
        }catch (Exception e){//异常类型必须对应上,如果写别的异常还是报异常
            System.out.println("出现异常,不要着急");
        }
     //   System.out.println(num);num在try的结构中,调不了,可以把num声明在try外面然后在try里面赋值
        System.out.println(num);
        System.out.println("hello---2");
    }
}

finally的使用

FinallyTest类

public class FinallyTest {
    @Test
    public void test2(){
        try {
            File file = new File("Hello.txt");
            FileInputStream fis = new FileInputStream(file);
            int data=fis.read();
            while (data!=-1){
                System.out.println((char)data);
                data=fis.read();
            }
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @Test
    public void testMethod(){
        int num=method();
        System.out.println(num);
    }
    public int method(){
        try {
            int[] arr = new int[10];
            System.out.println(arr[10]);
            return 1;
        }catch (ArrayIndexOutOfBoundsException e){
            e.printStackTrace();
            return 2;
        }finally {
            System.out.println("我一定会被执行");
            return 3;//三个return,return的是3
        }
    }
    @Test
    public void test1(){
     try {
         int a = 10;
         int b = 0;
         System.out.println(a / b);
     }catch (ArithmeticException e){
      //   e.printStackTrace();
         int[] arr = new int[10];
         System.out.println(arr[10]);//算术异常后又出现了异常,正常应该要退出了
     }catch (Exception e) {
         e.printStackTrace();
     } finally {
         System.out.println("我好帅啊");
     }
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/271043.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号