前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java异常处理

Java异常处理

作者头像
程序员的时光001
发布2020-07-14 16:48:58
1K0
发布2020-07-14 16:48:58
举报

Exception是检查型异常,在程序中必须使用try...catch进行处理;

RuntimeException是非检查型异常,例如NumberFormatException,可以不使用try...catch进行处理,但是如果产生异常,则异常将由JVM进行处理;

RuntimeException用法:

package m01d01;

public class Exception01 {

  public static void testRuntimeException() throws RuntimeException{
    throw new RuntimeException("运行时异常");
  }

  public static void testException() throws Exception{
    throw new Exception("编译时异常");
  }

  public static void main(String[] args) {
    testRuntimeException();


  }
}

可以看见,运行时异常可以不用 try...catch进行处理,仍然能运行成功;

结果为:

但是Exception必须要捕获,否则编译就会报错:

使用try...catch进行处理后:

package m01d01;

public class Exception01 {

  public static void testRuntimeException() throws RuntimeException{
    throw new RuntimeException("运行时异常");
  }

  public static void testException() throws Exception{
    throw new Exception("编译时异常");
  }

  public static void main(String[] args) {

    try {
      testException();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    testRuntimeException();
  }
}

输出结果:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-11-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员的时光 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档