Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Java
  3. Question
Java

How can I use Java try without catch?

Asked by Naveena N Oct 12, 2022 651 views 1 answer
Share

About this question

The classical way to program is with try ... catch. When is it appropriate to use try without catch?

In Python the following appears legal and can make sense:

try:

  #do work
finally:
  #do something unconditional
However, the code didn't catch anything. Similarly one could think in Java it would be as follows:
try {
    //for example try to get a database connection
}
finally {
  //closeConnection(connection)
}

It looks good and suddenly I don't have to worry about exception types, etc. If this is good practice, when is it good practice? Alternatively, what are the reasons why this is not good practice or not legal? (I didn't compile the source. I'm asking about it as it could be a syntax error for Java. I checked that Python surely compiles.)

A related problem I've run into is this: I continue writing the function/method, at the end of which it must return something. However, it may be in a place which should not be reached and must be a return point. So, even if I handle the exceptions above, I'm still returning NULL or an empty string at some point in the code which should not be reached, often the end of the method/function. I've always managed to restructure the code so that it doesn't have to return NULL, since that absolutely appears to look like less than good practice.

Your answer

1 Answer

More Java discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Java Blogs

Guides, tips and career advice on Java from JanBask experts.