• 技术文章 >java >java基础

    java中try-catch的使用

    小妮浅浅小妮浅浅2021-02-21 10:16:35原创15430

    本教程操作环境:windows7系统、java10版,DELL G3电脑。

    1.try和catch概念

    try -- 用于监听。将要被监听的代码(可能抛出异常的代码)放在try语句块之内,当try语句块内发生异常时,异常就被抛出。

    catch -- 用于捕获异常。catch用来捕获try语句块中发生的异常。

    2.try和catch用法

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    public class Demo1 {

      

        public static void main(String[] args) {

            try {

                int i = 10/0;

                  System.out.println("i="+i);

            } catch (ArithmeticException e) {

                  System.out.println("Caught Exception");

                System.out.println("e.getMessage(): " + e.getMessage());

                System.out.println("e.toString(): " + e.toString());

                System.out.println("e.printStackTrace():");

                e.printStackTrace();

            }

        }

    }

    try语句块中有除数为0的操作,该操作会抛出java.lang.ArithmeticException异常。通过catch,对该异常进行捕获。

    3.try-catch处理异常

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    private static void readFile(String filePath) {

    File file = new File(filePath);

    String result;

    BufferedReader reader;

    try {

    reader = new BufferedReader(new FileReader(file));

    while((result = reader.readLine())!=null) {

    System.out.println(result);

    }

    reader.close();

    } catch (IOException e) {

    e.printStackTrace();

    }}

    以上就是java中try-catch的使用方法,在程序出现Exception这类可以解决的错误时,我们可以通过try-catch的方法进行改变。

    专题推荐:java,try-catch
    上一篇:java switch和if语句的不同 下一篇:java finally处理异常

    相关文章推荐

    • case在java中支持字符串• java switch和if语句的不同

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网