Martijn Cour..
18
在构造对象时抛出异常,有两种选择:
在构造函数中
在初始化变量时
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
try
{ new Test(); } catch (Exception e) { e.printStackTrace(); }
try
{ new Test2(); } catch (Exception e) { e.printStackTrace(); }
try
{ new Test3(); } catch (Exception e) { e.printStackTrace(); }
}
static class Test
{
Object obj = getObject();
Object getObject()
{ throw new RuntimeException("getObject"); }
}
static class Test2
{
Test2()
{
throw new RuntimeException("constructor");
}
}
static class Test3
{
Object obj1 = null;
String str = obj1.toString();
}
}
生产:
java.lang.RuntimeException: getObject
at Main$Test.getObject(Main.java:24)
at Main$Test.(Main.java:22)
at Main.main(Main.java:9)
java.lang.RuntimeException: constructor
at Main$Test2.(Main.java:31)
at Main.main(Main.java:12)
java.lang.NullPointerException
at Main$Test3.(Main.java:38)
at Main.main(Main.java:15)