• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions

 
Brian O'Shea
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Going through some practice questions, one is very vague.
If a method throws an unchecked exception does code need to be added for it to compile and execute?

Wouldn't the answer depend on the definition of execute? Execute until the exception or execute successfully.

The above code would not execute successfully, only printing 1.


The above code would execute successfully, print 13.

So for the code to compile and execute, the code which could throw an unchecked exception would have to be in a try block of a try/catch. In the example above if the method was to declare the ArithmeticException in the method header the rest of the method would not execute.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian O'Shea wrote:If a method throws an unchecked exception does code need to be added for it to compile and execute?

The answer is short and simple: no. Unchecked exceptions are not subject to the handle-or-declare rule (which is enforced by the compiler). So you don't need to add code to compile and execute the code. It does not depend on the definition of "execute": either a program can be executed (no compiler errors) or not (compilation fails).
 
Brian O'Shea
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Roel.
 
Campbell Ritchie
Sheriff
Posts: 51344
86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree with Roel. At execution time there are four possibilities:-
  • Fail to execute, i.e. fail to start at all. Try code with no main method for that
  • Execute and fail to terminate, e.g. deadlock, infinite loop.
  • Execute and complete abruptly e.g. suffer an Exception
  • Execute and complete normally
  •  
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic