zoukankan      html  css  js  c++  java
  • java 异常处理

                           异常处理

     

    1,请阅读AboutException.java示例,然后了解java中实现异常处理的基础知识

    异常处理的格式为:

    try{

    这里用来写可能发生错误的语句

    若出现错误时会抛出一个异常对象

    }

    catch{

    try中发生异常时,try中的异常语句会跳转到此处

    这里用来处理抛出的错误

    不同的异常语句进入到不同的catch

    }

    Finally{

    无论是否有异常,这里的语句都会被执行

    }

    2,多层的异常捕获-1

    运行结果(自己的判断):

    ArrayIndexOutOfBoundsException/内层try-catch

    发生ArithmeticException

    程序运行结果:

    ArrayIndexOutOfBoundsException/内层try-catch

    发生ArithmeticException

     

    3,多层的异常捕获-2

    运行结果(自己的判断):

    发生ArithmeticException

    程序运行结果

    ArrayIndexOutOfBoundsException/外层try-catch

    4finally语句块一定会执行吗?

    不一定,若在catch语句中使程序退出,那么就不会执行finally语句块。

    5,阅读EmbedFinally.java示例,运行后观察其输出并进行总结

    当有多个try……catch……finally时,若外层出现错误且try块中的语句在内层的上面,那么内层的try……catch……finally都不会执行,此外finally语句块执行的顺序为总内层向外执行。

    课后作业2

     1 package 异常处理;
     2 import java.io.*;
     3 import java.util.Scanner;
     4 public class Result {
     5     public static void nextInt()throws Exception{
     6         
     7     }
     8     public static void result(int score)throws Exception{
     9         
    10         if(score<0){
    11             throw new Exception("成绩不能小于0");
    12         }
    13         if(score>100){
    14             throw new Exception("成绩不能大于100");
    15         }
    16         if(score>=90&&score<=100)System.out.println("优");
    17         else if(score>=80&&score<90)System.out.println("良");
    18         else if(score>=70&&score<80)System.out.println("中");
    19         else if(score>=60&&score<70)System.out.println("及格");
    20         else System.out.println("不及格");
    21     }
    22     public static void main(String[] args){
    23         try{
    24             System.out.println("请输入一个整数:");
    25             try{
    26                 BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
    27                 int score = Integer.parseInt(buf.readLine());
    28                 result(score);
    29             }catch(NumberFormatException e) { 
    30                 System.out.println("输入必须为整数"); 
    31             }
    32         }catch(Exception e){
    33             System.out.println(e.getMessage());
    34         }
    35         
    36     }
    37 
    38 }
  • 相关阅读:
    mysql decimal(10,2)对应java类型
    idea maven 配置spring boot dev-tools热部署
    在CentOS 8上安装Java 11(OpenJDK 11)和Java 8(OpenJDK 8)的方法
    关于mybatis-plus中Service和Mapper的分析
    Springboot测试类之@RunWith注解
    Get bit field from buffer as an integer / Set bit field in buffer from an integer
    A generic doubly linked list implementation
    Array helper
    Base64 Encoding/Decoding
    ffmpeg color_table[]
  • 原文地址:https://www.cnblogs.com/news1997/p/7845002.html
Copyright © 2011-2022 走看看