Java连载63-异常处理try...catch...、方法getMessageyu printStackTrace

1、处理异常的第二种方法java

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

语法:git

 

try{

  可能出现异常的代码;

}catch{

  处理异常的代码;

}catch{

 

 

注意:github

(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异常。ui

 

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();

   }

}

 

 

改正方式就是改一行代码spa

 

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

 

 

2、getMessage与printStackTrace方法.net

 

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");

  }

}

3、源码:

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.欢迎关注微信公众号:傅里叶变换,我的公众号,仅用于学习交流,后台回复”礼包“,获取大数据学习资料

 

相关文章
相关标签/搜索