zoukankan      html  css  js  c++  java
  • Java连载63-异常处理try...catch...、方法getMessageyu printStackTrace

    一、处理异常的第二种方法

    1.try......catch...

    语法:

     
    
    try{
    
      可能出现异常的代码;
    
    }catch{
    
      处理异常的代码;
    
    }catch{
    
     

    注意:

    (1)引入了什么异常,catch里面就要写清楚,出现了什么异常该怎么办;

    (2)异常也可以有父类和子类,按照从上到下的顺序进行捕捉;因此当写异常的时候需要按照从上到下,从小到大(也就是从子类异常到父类异常)

    (3)try,,,catch....中最多执行一个catch语句块,执行结束之后try.....catch....就结束了。

     
    
    package com.bjpowernode.java_learning;
    
    import java.io.*;
    
    public class D63_1_TryCatchExercise {
    
      public static void main(String[] args) {
    
        try {
    
          FileInputStream f1 = new FileInputStream("C:\user");
    
          f1.read();
    
        }catch(ArithmeticException a) {
    
         
    
        }catch(FileNotFoundException f) {
    
         
    
        }
    
      }
    
    }

    对于throws处理的异常,要对代码块中可能出现的异常进行覆盖,否则就会报错,例如:原因就是没有处理read()方法引入的IOException异常。

    package com.bjpowernode.java_learning;
    
    import java.io.*;
    
    public class D63_1_TryCatchExercise {
    
      public static void main(String[] args) throws FileNotFoundException{
    
          FileInputStream f1 = new FileInputStream("C:\user");
    
          f1.read();
    
       }
    
    }

    改正方式就是改一行代码

    public static void main(String[] args) throws FileNotFoundException,IOException

    二、getMessage与printStackTrace方法

    package com.bjpowernode.java_learning;
    
     
    
    import java.io.*;
    
     
    
    public class D63_2_MethodOfgetMessageAndprintStackTrace {
    
      public static void main(String[] args) {
    
        try {
    
          FileInputStream f1 = new FileInputStream("C:\fjdoa");
    
        }catch (FileNotFoundException e) {
    
          //打印异常堆栈信息
    
          //一般情况下都会使用该方法去调试程序
    
          e.printStackTrace();
    
          //下面这个方法与上面这个方法的功能其实是一样的,但是通常使用上面的方法,因为上面的方法能够打印出更加详细的信息
    
          String msg = e.getMessage();
    
          System.out.println(msg);
    
        }
    
        System.out.println("ABC");
    
      }
    
    }

    三、源码:

    D63_1_TryCatchExercise.java

    D63_2_MethodOfgetMessageAndprintStackTrace.java

    https://github.com/ruigege66/Java/blob/master/D63_1_TryCatchExercise.java

    https://github.com/ruigege66/Java/blob/master/D63_2_MethodOfgetMessageAndprintStackTrace.java

    2.CSDN:https://blog.csdn.net/weixin_44630050

    3.博客园:https://www.cnblogs.com/ruigege0000/

    4.欢迎关注微信公众号:傅里叶变换,个人公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料

     

  • 相关阅读:
    gcd
    Kuglarz
    三分题解
    杜教筛
    第一组dp解题报告
    dp总结1
    cf-BitwiseXor
    6.6总结
    图论总结
    CF1309总结
  • 原文地址:https://www.cnblogs.com/ruigege0000/p/12078834.html
Copyright © 2011-2022 走看看