• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
战神何少
博客园    首页    新随笔    联系   管理    订阅  订阅
捕获异常和抛出异常

异常处理五个关键字

try(监控区域)  catch(捕获异常)  finally(始终执行)  throw(方法体里面用) throws(方法名后面用)

public class demo4 {
    public static void main(String[] args) {
        int a = 1;
        int b = 0;

        //捕获异常 ,要从小到大的顺序捕获,否则程序报错   快捷键: ctrl+alt+T
        try{//try监控区域
            //这个必定是异常
            System.out.println(a/b);
        }catch(Error e){ //catch(想要捕获的异常) 捕获异常
            System.out.println("Error");
        }catch (Exception e){
            System.out.println("Exception");
        }catch (Throwable t){
            System.out.println("Throwable");
        } finally {  //finally  处理善后工作
            System.out.println("都会执行finally");
        }
//finally  可以不要finally 假设IO,资源,关闭
 
public class demo4 {
    public static void main(String[] args) {
        new demo4().test(1,0);

    }
    public void test( int a,int b){
        if(b==0){
            throw new ArithmeticException();//主动抛出异常,在方法体用
        }

    }
}
public class demo4 {
    public static void main(String[] args) {

        try {
            new demo4().test(1, 0);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        }

    }

    //在方法名后面用throws 抛出异常
    public void test(int a, int b) throws ArithmeticException {
        System.out.println(a/b);
    }
}

 

  
posted on 2020-06-19 02:09  战神何少  阅读(177)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2026
浙公网安备 33010602011771号 浙ICP备2021040463号-3