6 ms·
Putting it in a static block is bad advice, there are many other places you could put initialization. What happens if a static block throws an exception is tha
by sfjailbird 13y ago
Putting it in a static block is bad advice, there are many other places you could put initialization.
What happens if a static block throws an exception is that the class will not be loaded, and every other time the code refers to the class it will get a ClassDefNotFoundException, which can lead to a 'fun' time tracing the actual issue. Hence why static blocks are not used very much (though it can be convenient).
- AYBABTME 13y agoThe idea is that if an exception has to be thrown, it will throw as early as possible, making it pretty obvious during development that there's a bug - whenever you try to run your app it will exit with an error about the MalformedUrl. Notice I said he/she should catch the exception in the static block and log it, pretty hard to have an issue tracking where the error comes from. You can't check at compile time that the Url is valid, but if as soon as you load the program, it crashes with this exception, it will be hard to ignore and the mistake won't be hidden. Since you catch the exception that's thrown a static time, there's no ClassDefNotFoundException. See examples of this concept in Go: http://golang.org/pkg/regexp/#MustCompile http://golang.org/pkg/regexp/#MustCompile http://golang.org/pkg/text/template/#Must http://golang.org/pkg/text/template/#Must The better solution would be to have a compile time error, but I don't think Java can do that.