What does signify in a Java exception?

前端 未结 2 1924
悲&欢浪女
悲&欢浪女 2020-12-10 12:04

What does signify in a Java exception?

For example:

BlahBlahException...

at java.io.FileInputStream.(FileInput         


        
2条回答
  •  佛祖请我去吃肉
    2020-12-10 12:18

    That the exception is thrown in the construction of the object, there are two options:

    • in the constructor
    • while initializing variables

    Check out this demo I wrote: http://ideone.com/Mm5w5


    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();
            }
    }
    

    Produces:

    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)
    

提交回复
热议问题