I initially started programming in college and learnt vb.net. Now I have decided to make the move to Java and have some queries. In vb, the try catch statement is laid out as follows
try
Catch ex as exception
finally
End catch
but from the java website (https://docs.oracle.com/javase/tutorial/essential/exceptions/putItTogether.html) i found that in java you use two catches like so:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
i was hoping someone could explain why you need two catches in java and what do the respective catches do/catch.
Thanks.
The code that is on the page that is in link i have modified it with single exception. Problem here is that in this case you will not able to know that exception is where whether due to
just you know that a exception occurs
Let us understand the concept it is better to know why the code fails due to which particular type of exception whether
Now The Code with handling of different Exception
Here we could come to know that whether it fails due to creation of file at location
error printed as
Next Case
Now when i comment the line
then it clearly says that it fails for index out of bound exception
So for the purpose of debugging the application properly and efficiently it is good.
I have created condition for the other type of exception
In Java, you can use multiple
catch
blocks.It doesn't necessarily means you have to.
It depends on the code your have in the
try
block, and how many checkedException
s it may potentially throw (or even uncheckedException
s if you really want to catch that, typically you don't and you don't have to).One bad practice is to use a single handler for general
Exception
(or worse,Throwable
, which would also catchRuntimeException
s andError
s):The good practice is to catch all potentially thrown checked
Exception
s.If some of them are related in terms of inheritance, always catch the child classes first (i.e. the more specific
Exception
s), lest your code won't compile:Also take a look at Java 7's multi-catch blocks, where unrelated
Exception
s can be caught all at once with a|
separator between eachException
type:Note
In this example you linked to, the first code snippet below Putting it all together may arguably be considered as sub-optimal: it does catch the potentially thrown
Exception
s, but one of them is anIndexOutOfBoundsException
, which is aRuntimeException
(unchecked) and should not be handled in theory.Instead, the
SIZE
variable (or likely constant) should be replaced by a reference to the size of theList
being iterated, i.e.list.size()
, in order to preventIndexOutOfBoundsException
from being thrown.I guess in this case it's just to provide an example though.