[Java] Exception Handling

A, Java Exception
anomaly is fundamental errors in the program, but not all errors are abnormal and wrong sometimes be avoided.
1. Processing Exception if ... else ...

package edu.xalead;

public class Caculate {
    private static boolean isNum(String num) {
        for (int i = 0; i < num.length(); i++) {
            char t = num.charAt(i);
            if (t < 48 || t > 57) {
                return false;
            }
        }
        return true;
    }

    /**
     * 主函数的中的String是声明一个字符变量
     * 参数args是用来接收命令行参数的行参数的
     *
     * @param args
     * 如:对两数求商
     */
    public static void main(String[] args) {
        if (args != null && args.length >= 2) {
            String num1 = args[0];
            String num2 = args[1];
            if (isNum(num1) && isNum(num2)) {

                /**
                 * 字符串中的一种用法,将字符串转换成数值
                 */

                int n1 = Integer.parseInt(num1);
                int n2 = Integer.parseInt(num2);
                if (n2 != 0)
                    System.out.println(n1 / n2);
                else
                    System.out.println("除数不能为0");
            } else {
                System.err.println("两个参数必须是数字");
            }
        } else {
            System.out.println("必须有命令行参数,且参数个数为两个");
        }
    }
}

For example, the above code, we need a lot of if ... else ... statements one by one handle exceptions, so apparently handle the exception, the code is too redundant, so the Java language in the original design to take into account these problems, exception handling framework of scheme, all exceptions can be used to represent a type, different types of abnormality corresponding to a subclass.
2. try ... catch ... capture of exception handling
general structure
try {
  program code
  } catch (Exception variable name of a type of abnormality) {
  program code
  } catch (Exception Type 2 abnormality variable name 2) {
  }
The basic process is encased in a try block of statements to be monitored, if an exception occurs in the try block, the exception is thrown, the catch block code may be captured and exception handling; also part of the system to generate an abnormality automatically thrown in the Java Runtime.
may have a plurality of catch statement for matching a plurality of abnormality, the one on a plurality of matches, perform the catch block is performed only when the abnormality match.
Such as:

 public static void main(String[] args) {
        try {
            String num1 = args[1];
            String num2 = args[1];
            int n1 = Integer.parseInt(num1);
            int n2 = Integer.parseInt(num2);

            System.out.println(n1 / n2);
        }catch (ArrayIndexOutOfBoundsException e){//数组越界异常
            e.printStackTrace();//打印栈帧中的信息
        }catch (NumberFormatException e){//数字格式化异常
            e.printStackTrace();
        }catch (ArithmeticException e) {//数学异常
            e.printStackTrace();
        }
    }

Is simply try to monitor use; to capture the catch
3. The above three base classes are abnormal Exception
(. 1) exception hierarchy
Here Insert Picture Description
where Error we can not handle exceptions, such as the virtual machine error;
Exception is that we can handle abnormality, which is the run-time exception RuntimeException, handling mandatory, not processed will not compile
such as:
controlled abnormal, non-operation exception
Here Insert Picture Description
divestiture
Here Insert Picture Description
(2) common exceptions
a null pointer exception:

 public static void main(String[] args) {
        String s = null;
        System.out.println(s.length());
    }

Here Insert Picture Description
b. Class translation exception

public class Animal {
}

public class Bird extends Animal {
    public void out(){
        System.out.println("A");
    }
}

public class Fish extends Animal {
    public void in(){
        System.out.println("鱼");
    }
}

test

public static void main(String[] args) {
        Animal a = new Bird();
        /**
         * 父类引用只能调用自己的东西,不能调用子类的东西
         * 如果想要调用子类的东西,只能将父类引用强制转换成子类,才能调用子类方法
         */
        ((Bird) a).out();
        a = new Fish();
        ((Fish) a).in();
        /**
         * 代码执行到这里,a保存的是Fish,Fish里面没有out方法
         * 所以这行错误
         */
        ((Bird) a).out();

    }
}

Abnormal (class cast exception)
Here Insert Picture Description
with the keyword throw throw an exception:

public class 抛出关键字 {
    public static void main(String[] args) {
        try {
            String num1 = args[0];
            String num2 = args[1];

            int n1 = Integer.parseInt(num1);
            int n2 = Integer.parseInt(num2);
            if(n2 == 5){
               throw new RuntimeException("我这里除5也不行");//用new给异常对象分配内存
            }
            System.out.println(n1 / n2);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_44084434/article/details/90477442