№11:Java异常处理

作者: Deque | 来源:发表于2017-04-07 16:28 被阅读0次

    异常

    意外处理手段:

    1.利用方法的特殊返回值处理意外

    • map.get()返回null表示每有找到

    • read() 返回0~255正常,返回 -1表示意外,文件的末尾

    • readLine() 正常返回字符串,意外返回null

    • ......

    • 优点:简单

    • 缺点:状态不明确

    2.利用异常返回特殊情况

    • Date d = fmt.parse(str) 正常返回日期

    try-catch

    案例:

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String str = "一九三七";
        Date d;
        try{
            d = fmt.parse(str);
        }catch(ParseException e){
            //一但try代码中出现了ParseException,就执行catch代码块
            System.out.println("替换系统时间");
            d = new Date();
        }
        
        System.out.println(d);
    

    多个try-catch

    案例:

        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        String str = "一九三七";
        String s = "55";
        Date d = null;
        int age = 0;
        try{
            d = fmt.parse(str);
            age = Integer.parseInt(str);
        }catch(ParseException e){
            //一但try代码中出现了ParseException,就执行catch代码块 处理日期·解析异常
            System.out.println("替换系统时间");
            d = new Date();
        }catch(NumberFormatException e){
            System.out.println("处理数字解析异常");
            age = 18;
        }
        
        System.out.println(d);
        System.out.println(age);
    

    异常的捕获和处理

    Throwable,Error和Exception

    • Java异常结构中定义有Throwable类,Ex

    相关文章

      网友评论

        本文标题:№11:Java异常处理

        本文链接:https://www.haomeiwen.com/subject/qovhattx.html