Java from entry to the master Chapter 12 Exception Handling

table of Contents

abnormal

Common exceptions Java

Custom exception

Runtime exception


abnormal

try-catch-finally

  • e.getMessage (); error output properties
  • e.toString (); output type and nature
  • e.printStackTrack (); indicate the type of anomaly, nature, stack level and location appear in the program
  • catch exception capture sequence
package ex12_Exception;


public class Take {
    public static void main(String[] args) {
        try {  //try语句中包含可能出现异常的代码
            String str = "hi";
            System.out.println("str: " + str);
            int age = Integer.parseInt("20L");
            System.out.println("age: " + age);
        } catch (Exception e) {  //获取异常信息
            e.printStackTrace();  //输出异常性质
        }
        System.out.println("program over");
    }
}

Common exceptions Java

Custom exception

package ex12_Exception;

class MyException extends Exception {  //创建自定义异常,继承Exception
    public MyException(String ErrorMessage) {  //构造方法
        super(ErrorMessage);  //父类构造方法
    }
}

public class Tran {
    static int avg(int number1, int number2) throws MyException {
        if (number1 < 0 || number2 < 0) {  //判断是否满足条件
            throw new MyException("不可使用负数");  //抛出异常信息
        }
        if (number1 > 100 || number2 > 100) {
            throw new MyException("数值太大了");
        }
        return (number1 + number2) / 2;
    }

    public static void main(String[] args) {
        try {  //处理可能出现异常的代码
            int result = avg(102, 150);  //调用avg()方法
            System.out.println(result);
        } catch (MyException e) {
            System.out.println(e);  //输出异常信息
        }

    }
}

Runtime exception

Each package Java class libraries are defined exception, all of these classes are subclasses of Throwable, Throwable derived two sub-classes, Exception class and the class Error

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Published 46 original articles · won praise 0 · Views 1026

Guess you like

Origin blog.csdn.net/weixin_37680513/article/details/103405992