What does signify in a Java exception?

前端 未结 2 1915
悲&欢浪女
悲&欢浪女 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.<init>(Main.java:22)
        at Main.main(Main.java:9)
    java.lang.RuntimeException: constructor
        at Main$Test2.<init>(Main.java:31)
        at Main.main(Main.java:12)
    java.lang.NullPointerException
        at Main$Test3.<init>(Main.java:38)
        at Main.main(Main.java:15)
    
    0 讨论(0)
  • 2020-12-10 12:22

    <init>

    is called

    Instance Initialization method

    which is created by your java compiler from the constructor you have defined. Though it is not valid method definition, your JVM expects this and anything that you put in the constructor will be executed in method. So when you an exception with from , you can be sure that it is from the constructor of the executed java class. Read more about this on Bill venner's design technique articles on Object Initialization.

    0 讨论(0)
提交回复
热议问题