zoukankan      html  css  js  c++  java
  • 2.异常处理机制

    异常处理机制:
    抛出异常
    捕获异常
    异常处理的5个关键字 try、catch、finally、throw、throws
    try、catch、finally、

     1 package com.exception;
     2 
     3 public class Demo01 {
     4     public static void main(String[] args) {
     5 
     6         //选中代码,快捷键:Ctrl+Alt+t
     7         int a = 1;
     8         int b = 0;
     9 
    10         //假设要捕获多个异常:需从小到大捕获!否则报错已被捕获。
    11 
    12         try {//try可以理解为监控区域
    13             System.out.println(a / b);
    14         } catch (Error e) {//catch(想要捕获的异常类型!)叫做捕获异常
    15             System.out.println("Error");
    16         } catch (Exception e) {
    17             //System.out.println("Exception");
    18             //System.exit(0);//程序结束
    19             e.printStackTrace();//打印错误的栈信息
    20         } catch (Throwable t) {
    21             System.out.println("Throwable");
    22         } finally {//处理善后工作,无论出不出异常,finally中的语句终究会执行
    23             System.out.println("finally");
    24         }
    25 
    26         //finally 可以不要finally,假设IO,资源,关闭!
    27 
    28     }
    29 
    30     public void a() {
    31         b();
    32     }
    33 
    34     public void b() {
    35         a();
    36     }
    37 }
    throw、throws

     1 package com.exception;
     2 
     3 public class Test {
     4     public static void main(String[] args) {
     5 
     6         //用 try catch 捕获后程序会正常执行,否则停止运行抛出异常
     7         try {
     8             new Test().test(1, 0);
     9         } catch (ArithmeticException e) {
    10             e.printStackTrace();
    11         }
    12     }
    13 
    14 
    15     //假设这个方法中处理不了这个异常。方法上抛出异常
    16     public void test(int a, int b) throws ArithmeticException {
    17         if (b == 0) {//throw throws
    18             throw new ArithmeticException();//主动抛出异常,一般在方法中使用
    19         }
    20     }
    21 }
     
  • 相关阅读:
    【强行点出机械师天赋,修复无脸男储钱罐】
    【自由随想录(二)】
    【自由随想录(一)】
    iOS Alamofire插件使用方法
    iOS获取设备ip地址(OC版)
    获取位置
    objective-c 开发最简单的UITableView时数据进不去的问题
    java 获取真实IP
    数据库添加外键
    mysql 清库
  • 原文地址:https://www.cnblogs.com/duanfu/p/12222697.html
Copyright © 2011-2022 走看看