zoukankan      html  css  js  c++  java
  • 廖雪峰Java3异常处理-1错误处理-2捕获异常

    1捕获异常

    1.1 finally语句保证有无错误都会执行

    try{...}catch (){...}finally{...}

    • 使用try...catch捕获异常
    • 可能发生异常的语句放在try{...}中
    • 使用catch捕获对应的Exception及其子类

    1.2 捕获多个异常

    try{...} catch() {...} catch(){...}finally{..}
    使用多个catch子句:

    • 每个catch捕获对应的Exception及其子类
    • 从上到下匹配,匹配到某个catch后不再继续匹配

    注意:catch的顺序非常重要,子类必须写在前面:
    try{...} catch(IOException e){...} catch(UnsupportedEncodingException e){...}
    UnsupportedEncodingException是IOExcetion的子类,这样UnsupportedEncodingException永远都不会被捕获到

    import java.io.*;
    import java.lang.String;
    
    public class Main {
        public static void main(String[] args) {
            process("abc");
            process("0");
        }
        static void process(String s) {
            try{
                int n = Integer.parseInt(s);
                int m = 100 / n;
            }catch(NumberFormatException e){
                System.out.println(e);
                System.out.println("Bad input");
            }catch (ArithmeticException e){
                System.out.println(e);
                System.out.println("Bad input");
            }finally {
                System.out.println("end process");
            }
        }
    }
    

    1.3 multi-catch

    如果某些异常的处理逻辑相同:

    • 不存在继承关系,必须编写多条catch子句,可以用 " | " 表示多种Exception
    import java.lang.String;
    
    public class Main {
        public static void main(String[] args) {
            process("abc");
            process("0");
        }
        static void process(String s) {
            try{
                int n = Integer.parseInt(s);
                int m = 100 / n;
            }catch(NumberFormatException|ArithmeticException e){
                System.out.println(e);
                System.out.println("Bad input");
            }finally {
                System.out.println("end process");
            }
        }
    }
    

    2.总结

    • catch子句的匹配顺序非常重要,子类必须放在前面
    • finally子句保证有无异常都会执行
    • finally是可选的
    • catch可以匹配多个非继承关系的异常(JDK >= 1.7)
  • 相关阅读:
    要发布游戏啦,平台要 3000个6位不重复的验证码 看我怎么做!!!
    数字化婚姻配对尝试
    java 和 .NET 的 类继承方面 的不同
    Asp.Net Core 实现谷歌翻译ApI 免费版
    Asp.Net Core 全局模型验证
    Asp.Net Core 下 Newtonsoft.Json 转换字符串 null 替换成string.Empty
    Windows 10 远程连接出现函数错误 【这可能由于CredSSP加密Oracle修正】
    矫正系统时间
    linux 安装WildFly 及可能遇到的问题
    ubuntu 安装 jdk-7
  • 原文地址:https://www.cnblogs.com/csj2018/p/10306057.html
Copyright © 2011-2022 走看看