Extra semicolon in catch block - java

I am reviewing various coding styles of GitHub authors to learn and get inspiration and this one is puzzling me. One author is consistently using an extra semicolon within locally handled catch block.
catch (SpecificException e) {
;
}
when wanting to ignore exceptions locally, I would just write
catch (SpecificException e) {}
As there is no difference between those two, so why one would use the extra semicolon?

; is an empty statement, so doesn't matter how many of those you would add.

There is no need to add an extra ; to denote empty catch block. The way you used should be preferred, and it is more clear. The extra ; is simply absurd.
Having said that, both the styles of catch block should be avoided. You should not have an empty catch block. That does more harm than good. You should at least have your catch block as:
catch (Exception e) {
e.printStackTrace();
}
Apart from that, you should try not to have a catch block to catch all kinds of Exceptions. You should create catch blocks for specific types of exception, so that you can handle them in different ways.

It's personal preference, the author might use that so an empty catch block is more noticeable.

Firstly, why have a catch block to do nothing with it. That being said, if I for whatever reason have an empty catch block I do it as catch (Exception) {}
This just changes is so that it still recognizes the empty catch block, but doesn't give me warnings that 'e' is initialized but never referenced.

It could be personal preference as if you check the java doc for Calendar.getInstance() method you will notice that theya are using same coding style preference.
public static Calendar getInstance(TimeZone arg, Locale arg0) {
return createCalendar(arg, arg0);
}
private static Calendar createCalendar(TimeZone arg, Locale arg0) {
CalendarProvider arg1 = LocaleProviderAdapter.getAdapter(CalendarProvider.class, arg0)
.getCalendarProvider();
if (arg1 != null) {
try {
return arg1.getInstance(arg, arg0);
} catch (IllegalArgumentException arg6) {
;
}
}

Related

What are the restriction for code inside catch block

So are there any specific restrictions for writting code inside catch block?
PS. This question was asked by my friend's java programming teacher on the exam.
In this feature, now you can catch multiple exceptions in single catch block. Before java 7, you was restricted to catch only one. To specify the list of expected exceptions a pipe (‘|’) character is used.
Lets understand using an example.
try
{
//Do some processing which throws NullPointerException; I am sending directly
throw new NullPointerException();
}
//You can catch multiple exception added after 'pipe' character
catch(NullPointerException | IndexOutOfBoundsException ex)
{
throw ex;
}
Remember: If a catch block handles more than one exception type, then the catch parameter is implicitly final. In this example, the catch parameter ex is final and therefore you cannot assign any values to it within the catch block.
According to JLS:
CatchClause:
catch ( {VariableModifier} CatchType Identifier ) Block
So, you can write anything you can write in any other block.

Exception hierarchy/try-multi-catch

try {
throw new FileNotFoundException();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
Can someone tell me why the second catch block is not considered as unreachable code by the compiler? But in the following case:
try {
throw new FileNotFoundException();
} catch (Exception e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
The second catch block is considered unreachable?
After all, FileNotFoundException comes under IOException, just as it comes under Exception.
Edit Please clarify:
The compiler will know an exception is thrown by a method based on the method's throws clause. But it may not necessarily know the specific type of exception (under that class of exception). So if a method throws exception 'A', compiler won't know if the actual exception is 'A' or a subtype of 'A' because this is only determined at runtime. The compiler however will know that an exception of type 'X' is never thrown, so giving a catch block for X is erroneous. Is this right?
The compiler cannot assume that the only possible exception thrown from your try block will be a FileNotFoundException. That's why it doesn't consider the 2nd catch block to be unreachable in your first code sample.
What if, for some unknown reason, a RuntimeException gets thrown while creating the FileNotFoundException instance (entirely possible)? What then?
In your first code sample, that unexpected runtime exception would get caught by the 2nd catch block, while the 1st block would take care of the FileNotFoundException if it gets thrown.
However, in your 2nd code sample, any and all exceptions would get caught by the 1st catch block, making the 2nd block unreachable.
EDIT:
To better understand why the catch(Exception e) block in your first code is not considered unreachable by the compiler, try the following code, and notice how the the 2nd catch is definitely reachable:
public class CustomIOException extends IOException {
public CustomIOException(boolean fail) {
if (fail) {
throw new RuntimeException("the compiler will never know about me");
}
}
}
public static void main(String[] args) {
try {
throw new CustomIOException(true);
} catch(IOException e) {
System.out.println("Caught some IO exception: " + e.getMessage());
} catch(Exception e) {
System.out.println("Caught other exception: " + e.getMessage());
}
}
Output:
Caught other exception: the compiler will never know about me
TL;DR
The compiler considers that FileNotFoundException() may not be the only Exception thrown.
Explaination
JLS§11.2.3 Exception Checking
A Java compiler is encouraged to issue a warning if a catch clause can
catch (§11.2) checked exception class E1 and the try block
corresponding to the catch clause can throw checked exception class
E2, a subclass of E1, and a preceding catch clause of the immediately
enclosing try statement can catch checked exception class E3 where E2
<: E3 <: E1.
That means that if the compiler considers that the only exception possibly thrown by your catch block is a FileNotFoundException(), it will warn you about your second catch block. Which is not the case here.
However, the following code
try{
throw new FileNotFoundException();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){ // The compiler warns that all the Exceptions possibly
// catched by IOException are already catched even though
// an IOException is not necessarily a FNFException
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
This happens because the compiler evaluates the try block to determine which exceptions has the possibility to be thrown.
As the compiler does not warn us on Èxception e, it considers that other exceptions may be thrown (e.g RunTimeException). Since it is not the compiler's work to handle those RunTimeExceptions, it lets it slip.
Rest of the answer is intersting to read to understand the mechanism behind exception-catching.
Schema
As you may see, Exception is high in the hierarchy so it has to be declared last after IOException that is lower in the hierarchy.
Example
Imagine having an IOException thrown. As it is inherited from Exception, we can say IOException IS-A Exception and so, it will always be catched within the Exception block and the IOException block will be unreachable.
Real Life Example
Let's say, you're at a store and have to choose pants. The seller tells you that you have to try the pants from the largest ones to the smallest ones and if you find one that you can wear (even if it is not your size) you must take it.
You'll find yourself buying pants too large for your size and you'll not have the chance to find the pants that fits you.
You go to another store : there, you have the exact opposite happening. You can choose your pants from smallest to largest and if you find one you can wear, you must take it.
You'll find yourself buying pants at your exact size.
That's a little analogy, a bit odd but it speaks for itself.
Since Java 7 : multi-catch
Since Java 7, you have the option to include all the types of Exceptions possibly thrown by your try block inside one and only catch block.
WARNING : You also have to respect the hierarchy, but this time, from left to right.
In your case, it would be
try{
//doStuff
}catch(IOException | Exception e){
e.printStackTrace();
}
The following example, which is valid in Java SE 7 and later,
eliminates the duplicated code:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
The catch clause specifies the types of exceptions that the block can
handle, and each exception type is separated with a vertical bar (|).
First case:
catch (IOException e) { // A specific Exception
e.printStackTrace();
}
catch (Exception e) { // If there's any other exception, move here
e.printStackTrace();
}
As you can see, first IOException is catched. This means we are aiming at just one specific exception. Then in second catch, we aim for any other Exceptions other than IOException. Hence its logical.
In second:
catch (Exception e) { // Move here no matter whatever exception
e.printStackTrace();
}
catch (IOException e) { // The block above already handles *Every exception, hence this won't be reached.
e.printStackTrace();
}
We catched any exception (whether its IOException or some other Exception), right in the first block. Hence second block will not be reached because everything is already included in first block.
In other words, in first case, we aim at some specific exception, than at any other exceptions. While in second case, we first aim at all/any Exception, than at a specific exception. And since we already dealt will all exceptions, having a specific exception later won't make any logical sense.

why is it not possible to insert code between try and catch block?

i was asked a question in interview what happens if we put finally block between try and catch block i answered in that case compiler will think that there is no catch block and it will directly execute finally block.
Then he asked why is it not possible to put code between try and catch block?
Can you please help me...
Okay, first thing first - the compiler doesn't execute the code, it just compiles it, allowing it to be run by the JVM.
Empirically speaking, that wouldn't make too much sense, since if you have some code that you would want to put outside the try block but before the catch block, the code could just as well be placed in the try block. The thing is, it would just behave as it were in the try block anyway if you think about it.
Let's assume this is valid Java (this doesn't compile):
try {
throw new Exception();
}
System.out.println("Sup!");
catch(Exception e) { }
When the exception gets thrown, that line that prints out Sup! will still get skipped as the JVM is searching to jump to the appropriate exception handler to treat Exception. So, in a way, the code behaves just as it would if it were in the try {} block itself, which is why it wouldn't really matter where it is, and the Java specifies that this (now proven useless) construct is illegal.
Now what if that code after the try were to throw another exception itself? If it were valid code, it would behave just like a nested try...catch block in the original try block. Of course that once things start getting complicated, the approach where there is no clear connection between a try and a catch block could get fuzzy, and the JVM would end up not knowing which catch/finally belongs to which try block (especially since the handler doesn't have to be in the same function, or even in the same package!).
Well, the flippant answer is that the language spec forbids it.
But let's step back a bit and think about it a different way - what if you could do this?
try {
foo();
}
bar();
catch (Exception e) {
baz();
}
What could the semantics of this be? If we catch an exception in foo(), is baz() called? What about bar()? If bar() throws, do we catch the exception in that case?
If exceptions in bar() are not caught, and exception in foo() prevent bar() from running, then the construct is equivalent to:
try {
foo();
} catch (Exception e) {
baz();
}
bar();
If exceptions in bar() are caught, and exception in foo() prevent bar() from running, then the construct is equivalent to:
try {
foo();
bar();
} catch (Exception e) {
baz();
}
If exceptions in bar() are not caught, and exception in foo() do not prevent bar() from running (bar() is always executed), then the construct is equivalent to:
try {
foo();
} catch (Exception e) {
baz();
} finally {
bar();
}
As you can see, any reasonable semantics for this between-try-catch construct are already expressible without the need for a new - and rather confusing - construct. It's hard to devise a meaning for this construct that is not already redundant.
As an aside, one potential reason we can't do:
try {
foo();
} finally {
bar();
} catch (Exception e) {
baz();
}
could be that it does not reflect actual execution order - catch blocks run before the finally block. This allows catch blocks to make use of resources that the finally block might release later (for example, to request additional diagnostic information from a RPC object or something). Could be made to work the other way as well? Sure. Is it worth it? Probably not.
Well it would mean something like this :
try
{
somCode();
}
someMoreCode();
catch
{
}
What should this mean ?
This is not possible because it has no semantic, and therefore it has been decided to be syntaxically incorrect by language designers!
If you have a try you must have either catch or finally, as defined in the java language specification, 14.20 "The try Statement`
try and catch like .. if and else ..
so there is no need to add code between try and catch block

Try/Catch statement not catching exceptions

I'm trying to use a try/catch statement inside an inner class of an actionlistener but it does not catch the exceptions even when I deliberately trigger them. Here is the code excerpt:
btnPerformCalculation.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
double runtime = Math.abs(Double.parseDouble(txtRunTime.getText()));
double downtime = Math.abs(Double.parseDouble(txtDownTime.getText()));
double blockedtime = Math.abs(Double.parseDouble(txtBlockedTime.getText()));
double lineefficiency = 100 * runtime / (runtime + downtime + blockedtime);
try {
txtEfficiencyAnswer.setText(String.format("%.2f", lineefficiency));
} catch (Exception e) {
JOptionPane.showMessageDialog(frame, "Error:" + e.getMessage());
txtRunTime.setText("0");
txtDownTime.setText("0");
txtBlockedTime.setText("0");
}
}
});
The only exceptions that you are catching are in txtEfficiencyAnswer.setText(String.format("%.2f", lineefficiency));. All other calculations (e.g. transforming possibly null text values into doubles are done before the try-block, and therefore not caught.
Assuming that txtEfficiencyAnswer is either a JTextComponent or a JLabel, the only obvious reason for an exception in that block would be a NullPointerException if txtEfficiencyAnswer is null. If it is not null, then you will never enter the catch-block.
First, how are you sure that JOptionPane.showMessageDialog isn't throwing an exception? I recommend putting output or logging as the first statement in your catch. Second, not all "exceptions" are subclasses of Exception. Try using catch (Throwable e) to see if the specific problem you are having gets solved.
I do not recommend leaving the catch(Throwable e) in your code since that will catch very low level jvm problems as well. But it will at least help you understand what's happening.
Probably setText throw RuntimeException.
Change catch statement to catch (RuntimeException e)
Print stacktrace.

Exception handling try catch inside catch

I recently came across code written by a fellow programmer in which he had a try-catch statement inside a catch!
Please forgive my inability to paste the actual code, but what he did was something similar to this:
try
{
//ABC Operation
}
catch (ArgumentException ae)
{
try
{
//XYZ Operation
}
catch (IndexOutOfRangeException ioe)
{
//Something
}
}
I personally feel that it is some of the poorest code I have ever seen!
On a scale of 1 to 10, how soon do you think I should go and give him a piece of my mind, or am I over-reacting?
EDIT:
What he is actually doing in the catch, he is performing some operations which can/should be done when the initial try fails. My problem is with having a clean code and maintainability. Delegating the exception from the first catch to a different function or the calling function would be OK, but adding more code which may or may not throw an exception into the first catch, is what I felt was not good. I try to avoid multiple stacked "if-loop" statements, I found this equally bad.
Why is that bad? It's no different conceptually than:
void TrySomething() {
try {
} catch (ArgumentException) {
HandleTrySomethingFailure();
}
}
void HandleTrySomethingFailure() {
try {
} catch (IndexOutOfRangeException) {
}
}
Before you go over there and give him a piece of your brain (try the parietal lobe, it's particularly offensive) , what exactly are you going to say to him? How will you answer the proverbial "why?"
What's even more ironic is that when the jitter inlines this code, it will look exactly like your example.
-Oisin
Here is a case :
try{
//Dangerous Operation
} catch (AnyException ae) {
try {
//Do rollback which can fail
} catch (RollbackFailedException rfe) {
//Log that
}
} finally {
try {
//close connection but it may fail too
} catch (IOException ioe) {
//Log that
}
}
It's about the same thing as #x0n said. You might need to handle exception while try to close resources or while you're trying to resolve a situation brought by another exception.
Without knowing what the code does it's impossible to say. But it's not unusual to do this.
e.g. if you have to clear up resources whilst handling exceptions, that clear-up code itself may have the capability to throw exceptions.

Categories