1.异常
  1.1程序执行过程中出现的影响程序正常运行的现象
  1.2异常语法
    try{
      //代码块
    }catch(异常类型1 e1){
  
    }catch(异常类型2 e2){

    }...{

    }finally{

    }
  注意:try:表示可能出现异常的代码块
     catch:抓取异常,并进行处理
       可以抓取多个异常,异常的范围要从小到大抓取,并且只会执行第一个匹配的异常类型
     finally:最终的,不管是否出现异常,finally中的代码块始终会执行,
       除虚拟机停止(System.exit(1))这种情况外
  注意:finally和return的执行顺序:先执行return,把返回结果保存在返回结果区域,并没有返回,
    再执行finally完后,最后,把保存在结果区域的结果返回给调用者

运行结果:

异常(五)

 1 package Day12六;
 2 
 3 import java.util.InputMismatchException;
 4 import java.util.Scanner;
 5 import org.apache.log4j.Logger;
 6 
 7 public class Test12 {
 8     private static Logger logger=Logger.getLogger(Test12.class.getName());
 9     public static void main(String[] args) {
10         try{
11             
12             Scanner input=new Scanner(System.in);
13             System.out.print("请输入被除数:");
14             int num1=input.nextInt();
15             logger.debug("输入被除数:"+num1);
16             System.out.print("请输入除数:");
17             int num2=input.nextInt();
18             logger.debug("输入除数:"+num2);
19             System.out.println(String.format("%d/%d=%d", num1,num2,num1/num2));
20             logger.debug("输出运算结果:"+String.format("%d/%d=%d", num1,num2,num1/num2));
21         }catch(InputMismatchException e){
22             System.out.println("被除数和除数必须是整数"+e);
23         }catch(ArithmeticException e){
24             logger.error(e.getMessage());
25         }catch(Exception e){
26             logger.error(e.getMessage());
27         }finally{
28             System.out.print("感谢使用本程序!");
29         }
30     }
31     
32 }
代码示例

相关文章:

  • 2021-12-18
  • 2021-11-08
  • 2021-09-28
  • 2022-01-04
  • 2021-05-20
  • 2021-12-03
  • 2021-11-14
猜你喜欢
  • 2021-07-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-29
  • 2021-10-18
  • 2021-11-08
  • 2021-09-13
相关资源
相似解决方案