This week's book giveaways are in the Angular and TypeScript and Web Services forums.
We're giving away four copies each of Programming with Types and The Design of Web APIs and have the authors on-line!
See this thread and this one for details.
Win a copy of Programming with Types this week in the Angular and TypeScript forum
or The Design of Web APIs in the Web Services forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Bear Bibeault
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Junilu Lacar
  • Knute Snortum
  • Henry Wong
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Frits Walraven
  • Joe Ess
  • salvin francis

Why is try/final block not working as expected?

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone! Newbie here.

I am learning Java from Head First Java. I have completed upto exceptions. There is a "Code Magnets" exercise on page 349. After solving it I decided to have some fun with the code.

There is a statement in the chapter: "If you define a try block, you can pair it with a matching catch or finally block, or both." So this statement says a try/final block without the catch block will also work.

So I took the code from "Code Magnets" and pasted it in an online Java editor to test the above statement. The code normally goes like this:



Here the output will be if input is yes: thaws and if input is suppose no then output is throws

Now my code where I decided to test the above statement.



But to my surprise the code did not execute. I got an error:

Main.java:7: error: unreported exception MyEx; must be caught or declared to be thrown
               doRisky(test);
                      ^


Now I have read that by declaring an exception I can duck it. So I modified the code as:



Now the output is given as:

thw
Exception in thread "main" MyEx
at Main.doRisky(Main.java:19)
at Main.main(Main.java:7)


So finally it works as usual.

Can any kind soul explain to me why the previous code of mine did not work but the second one worked? According to me both codes should work as the statement said.
 
Rancher
Posts: 4405
47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
MyEx extends Exception, which means that it needs to be handled (as the compiler error says).
It can be handled either by catching it in a catch block, or by changing the method signature to show that it throws the exception.

Your second code works because you have told Java that the exception is being passed out of the method rather than being handled inside the method, by changing the signature to note the exception thrown.
 
Eric Kaiser
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dave Tolls wrote:MyEx extends Exception, which means that it needs to be handled (as the compiler error says).
It can be handled either by catching it in a catch block, or by changing the method signature to show that it throws the exception.

Your second code works because you have told Java that the exception is being passed out of the method rather than being handled inside the method, by changing the signature to note the exception thrown.



But the statement said: "If you define a try block, you can pair it with a matching catch or finally block, or both."

So by this I understand you don't have to handle the exception if it arises or not, finally() block will always run.
 
Sheriff
Posts: 14614
243
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Eric Kaiser wrote:"If you define a try block, you can pair it with a matching catch or finally block, or both."

So by this I understand you don't have to handle the exception if it arises or not, finally() block will always run.


It's not a question of whether or not the finally block will run. What you got there was a compile-time error because of the rule that checked exceptions must be either declared with throws or caught in a catch() block. Since you did neither, then the code will not compile. The presence or absence of a finally block is irrelevant.
 
Marshal
Posts: 66975
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I presume that passage will also have told you that a checked exception must be handled somehow. In this case you either need to declare the exception with a throws or you need both catch and finally.
 
Eric Kaiser
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Eric Kaiser wrote:"If you define a try block, you can pair it with a matching catch or finally block, or both."

So by this I understand you don't have to handle the exception if it arises or not, finally() block will always run.


It's not a question of whether or not the finally block will run. What you got there was a compile-time error because of the rule that checked exceptions must be either declared with throws or caught in a catch() block. Since you did neither, then the code will not compile. The presence or absence of a finally block is irrelevant.



I see. While reading on this try/final block topic I stumbled upon this piece of code online:



This code got executed without any issues but I did not expect this to. Why?

The output is given as:

Executing finally block
Exception in thread "main" java.lang.NullPointerException
at Main.print(Main.java:12)
at Main.main(Main.java:5)


Now this code differs from mine which did not execute in the case that here is no method which mentions an exception is being thrown of any kind for example:



But when I executed code with this change still the output remained same. Why?
 
Campbell Ritchie
Marshal
Posts: 66975
255
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is an unchecked exception. The compiler will allow it to compile without needing a catch, and the finally will be executed. I suggest you go through this part of the Java™ Tutorials.
 
Eric Kaiser
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:That is an unchecked exception. The compiler will allow it to compile without needing a catch, and the finally will be executed. I suggest you go through this part of the Java™ Tutorials.



Ok so if I get this right, if an exception occurs I need to handle it with the catch() except if it is a unchecked exception that gets a free pass from the compiler. Ultimately I conclude that whatever the exception maybe it is best to handle the exception with the catch() block.
 
Campbell Ritchie
Marshal
Posts: 66975
255
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the compiler can ignore an unchecked exception.

Eric Kaiser wrote:. . . whatever the exception maybe it is best to handle the exception with the catch() block.

In a lot of cases, particularly with unchecked exceptions, that wouldn't work at all well:-
  • 1: You usually can't predict what sort of unchecked exception you might suffer, so are you going to surround everything in try‑catches?
  • 2: You  may decide, “this isn't a good place to handle such an exception,” in which case it is better allowed to propagate to where it can be handled.
  • 3: It may be necessary to alter the original code to prevent the exception being thrown again, in which case there is no point in catching it. Again more common with unchecked exceptions.
  • Beware of error messages. If the end‑user gets a stack trace, they won't understand a word of it. Don't let that happen; give them a different sort of message. But for you as a developer, the stack trace is very useful.
     
    Junilu Lacar
    Sheriff
    Posts: 14614
    243
    Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Eric Kaiser wrote:Ultimately I conclude that whatever the exception maybe it is best to handle the exception with the catch() block.


    That would be the wrong conclusion. Go through the tutorials and understand what each kind of exception (checked vs. unchecked) is for. It's quite appropriate to allow unchecked exceptions to blow up and interrupt program execution while you're still developing and testing your program. In this case, you want that to happen because it allows you to find developer mistakes and fix them. As for checked exceptions, it may be appropriate to allow them to bubble up to a level where the decision on how to handle them makes sense. It all depends on the context.
     
    Eric Kaiser
    Greenhorn
    Posts: 6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks to Campbell Ritchie and Junilu Lacar! I understood why and what is happening in all the codes I posted.

    That would be the wrong conclusion. Go through the tutorials and understand what each kind of exception (checked vs. unchecked) is for. It's quite appropriate to allow unchecked exceptions to blow up and interrupt program execution while you're still developing and testing your program. In this case, you want that to happen because it allows you to find developer mistakes and fix them. As for checked exceptions, it may be appropriate to allow them to bubble up to a level where the decision on how to handle them makes sense. It all depends on the context.



    I don't know how to tag an user but this question is for Junilu Lacar or to anyone who can answer this. I get that unchecked exceptions are useful for the developer and also those exceptions usually happen when there is a mistake done by the developer in programming logic. But for checked exceptions why will you like to allow it? I mean we have to handle them in a catch block regardless or have to declare it. Unless I am debugging an application during development I don't think I will like to have checked exceptions arise as ultimately they won't allow to get the code compiled.

     
    Campbell Ritchie
    Marshal
    Posts: 66975
    255
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    If you have code which you know might go wrong, you are probably better with a checked exception. You know where something will go wrong and you know it has to be handled, so write throw new XYZException(...); boldly, and you can handle it somewhere more appropriate as Junilu and I said eariler.
     
    Marshal
    Posts: 24820
    60
    Eclipse IDE Firefox Browser MySQL Database
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator

    Eric Kaiser wrote:But for checked exceptions why will you like to allow it? I mean we have to handle them in a catch block regardless or have to declare it. Unless I am debugging an application during development I don't think I will like to have checked exceptions arise as ultimately they won't allow to get the code compiled.



    If you're only writing code which consists of a single main() method, then yes, you're not going to realize that there's a decision to make. But in a real application, there are lots of classes and lots of methods. And there's a design which says what classes are responsible for what.

    So you might have a method which connects to a URL and retrieves the content which that URL returns. Now there's a lot of things which can go wrong with that process, starting with not being able to connect to the URL for one of many reasons. So some kind of exception will be thrown if that happens. But should that exception be handled in the method?

    Okay, what should the content-retrieving method do if there's an exception? Well, remember that its purpose was to retrieve the content? Then that's what it should do, nothing else. It shouldn't catch the exception. It should simply allow the exception to be thrown to the calling method, at least in most reasonable designs. Then the calling method would work like this: Call the content-retrieving method; if it threw an exception then deal with it -- or else allow it to be thrown to its caller. Since I haven't said what the calling method is supposed to do, I don't have a design for it and therefore I can't say, yet, what it should do about exceptions. But that would certainly be part of its design.
     
    Campbell Ritchie
    Marshal
    Posts: 66975
    255
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    There are all sorts of things you can do if an exception is thrown; here are a few:-
  • 1: Log it
  • 2: Display an error message
  • 3: Display the stack trace.
  • 4: Cause a flag to be set so the memthod is called again (in a loop).
  • 5: Cause a different argument to be passed to the method.
  • 6: Request the user enter new information.
  • 7: Rethrow the exception.
  • 8: Throw a new (chained) exception.
  • 9: Allow the exception to propagate unchanged, taking no further action at the moment.
  • There are bound to be other actions you can take. You can do several of the above. But, as Paul, Junilu and I have hinted, in most cases it isn't possible to take any actions in the method the exception first appears in.
    Also remember, whichever action you take, who is going to see it? What the end‑user can understand is something completely different from what you as the developer find useful.
     
    Eric Kaiser
    Greenhorn
    Posts: 6
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thank you everyone! Noted down all the points in my head. Thanks again guys.
     
    Ranch Foreman
    Posts: 89
    4
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    May let me add an opinion (note: that's may way of seeing it - some may agree some may disagree): Exceptions, as the word says, are abnormal flow of execution. Their meaning (in most cases) is to signal that something gone "wrong". I put "wrong" in quotes as it should rather be read as: it went off a different path than intended. Exceptions should not be used for flow control. That means you shouldn't write code wich require an Exception to occur to work as you want it to. Many Exceptions can be avoided by careful check conditions upfront:
    - does directory X exist?
    - can you read it?
    - does file Y exist? (note: on unix you can can't check if a directory contains a file if you don't have read permissions on the directory)
    - can you read/write/execute the file?
    As you can see there're a few checks that can be done upfront to avoid Exceptions:
    - if you don't have permission to read the directory you can't check wether the file exists
    - it doesn't matter if the file exists if you don't have permissions for it
    What can go wrong? For example you just assume that the directory exist, that you have rights on it, that the file exist and that you have rights on it. So you just try to read from/write to the file - wich doesn't exist! So now you get the abnormal state that the file just isn't there and hence you get a FileNotFoundException. This could had be avoided with the mentioned checks before. It's a bad example as FileNotFoundException is a subclass of IOException wich you always have to handle but it serves the purpose. Any operations on files may throw IOException - but this should only the case in the event of severe hardware issues or a terminated network connection.
    I'd like to say this: Although in development often Exceptions just thrown or ignored for production code one should really understand what might could all go wrong in the field not simulated while development. Can you always ensure that the network connection wich a share rely on doesn't get terminated by a faulty switch? In this case an IOException is a severe issue caused by some malfunction wich is logical miles away. How do you know if it's just a file not found or a broken switch when you assume there will be no problem? That's you should not rely on Exceptions for flow control.
    In normal day to day use the user never should get an Exception. So, check upfront if the file exists and can be accessed so if it doesn't prompt the user to create a new one and reserve the severe issues for messages like: "Meltdown - call IT"

    Kris
     
    The human mind is a dangerous plaything. This tiny ad is pretty safe:
    Java file APIs (DOC, XLS, PDF, and many more)
    https://products.aspose.com/total/java
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!