Static modifiers and exceptions

  • 8
  • Locked
Let's throw some exceptions! In a static block, throw an Exception so that the class doesn't load and you see an error message instead of the value of the variable.
You can't complete this task, because you're not signed in.
Comments (6)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Karas Java Developer
6 May 2022, 00:27
Kudos to Muhammad Vahhaaj, to explain do not just throw something, code something that actually do that. Just remember the different types of Exeptions and use the one that is not detected during compiling time.
Jonaskinny Java Developer at Sandmedia
2 March 2022, 21:39
Had to resort to the solution in this case. I threw in both if (true) and else to get the second error from the JVM which I did, but the solution does not. Mine produces java: initializer must be able to complete normally java: unreachable statement Solution that passed validator does not produce the second error even though that is part of the requirements
Justin Smith
Level 39 , Greenfield, USA, United States
18 August 2021, 22:53
Condition 1 says "An exception (Exception)..." which suggests that the exception thrown must be a generic Exception rather than any of the child inherited Exception classes. However, the code will not even compile if you try to do it with Exception. It must be RuntimeException. I was stuck on this one for a while trying to make "throw new Exception();" work, and I think the condition is a little misleading in that sense.
Angel Angelov
Level 15 , Sofia, Bulgaria
6 August 2020, 13:42
I really don't see the point of this excercise. Why in any world would I want to purposefully make my program crash?
Muhammad Vahhaaj
Level 19 , Rawalpindi, Pakistan
29 July 2019, 06:42
So. If anyone is wondering the philosophy behind this concept. Then this comment can save you the time and give you the information. The static initializer block is supposed to run successfully because if it does not then the object will never reach its creation state(you can not work with the object). So if you directly throw an exception in the initializer block then it will give you error because it is supposed to run successfully. But here is the catch if you generate the exception in the if(<expression>) block then it shows a completely different behavior. if you put an unchecked exception(the one that need not to be catched and terminates the program in runtime, =>runtime exception in short) in if(true) { (in here) } then the program will run without an error and will compile successfully. Reason behind it is that an if block is either supposed to run or not so it just sort of ignores the if block and never checks whether there is an exception thrown. This is a bizarre bug.
Muhammad Vahhaaj
Level 19 , Rawalpindi, Pakistan
29 July 2019, 06:28
uhh, what?