What does <init> signify in a Java exception?

落爺英雄遲暮 提交于 2019-12-18 04:34:29

问题


What does <init> signify in a Java exception?

For example:

BlahBlahException...

at java.io.FileInputStream.<init>(FileInputStream.java:20)

回答1:


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)



回答2:


<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.



来源:https://stackoverflow.com/questions/11789990/what-does-init-signify-in-a-java-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!