A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

在new一个对象的时候,构造函数中抛出异常,那么这个对象会不会由于构造函数的中断而不被创建?

评分

参与人数 1技术分 +1 收起 理由
谭立文 + 1

查看全部评分

2 个回复

倒序浏览
这个肯定的  测试下
  1. public class TestException extends Exception
  2. {
  3.         TestException(String msg)
  4.         {
  5.                 super(msg);
  6.         }
  7. }

  8. class Test
  9. {
  10.         Test(int n) throws TestException
  11.         {
  12.                 if(n<0)
  13.                         throw new TestException("出错");

  14.         }
  15. }

  16. class  Demo
  17. {
  18.         public static void main(String[] args)
  19.         {
  20.                 Test t =null;
  21.                 try
  22.                 {
  23.                         t =new Test(1);
  24.                 }
  25.                 catch (Exception e)
  26.                 {
  27.                         System.out.println(e.toString());
  28.                 }
  29.                 System.out.println(t.toString());//如果出错时也创建对象则会返回对象引用,如果不创建对象则是空指针异常
  30.         }
  31. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
谭立文 + 1

查看全部评分

回复 使用道具 举报
class Test
{
         Test(int n) throws TestException
         {
                 if(n<0)
                         throw new TestException("出错");

        }
}

class  Demo
{
         public static void main(String[] args)
        {
                Test t =null;
                 try
                 {
                         t =new Test(1);
                 }
                 catch (Exception e)           //您好,我今天也刚学习到这里,对于异常处理也学习的是懂非懂的,在看你的代码的时候,我在这里有个疑问可以问一下吗?
                                     上面的代码已经抛出TestException异常。那这里的catch()为什么不直接接收TestException呢? 反而要去接收它的父类Exception来处理错误。
                 {
                         System.out.println(e.toString());
                 }
                 System.out.println(t.toString());
         }
}

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 赞一个!

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马