Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Try Catch block

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.

like image 645
User59 Avatar asked Aug 05 '26 21:08

User59


1 Answers

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 checked Exceptions it may potentially throw (or even unchecked Exceptions 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 catch RuntimeExceptions and Errors):

try {
    // stuff that throws multiple exceptions
}
// bad
catch (Exception e) {
    // TODO
}

The good practice is to catch all potentially thrown checked Exceptions.

If some of them are related in terms of inheritance, always catch the child classes first (i.e. the more specific Exceptions), lest your code won't compile:

try {
    // stuff that throws FileNotFoundException AND IOException
}
// good: FileNotFoundException is a child class of IOException - both checked
catch (FileNotFoundException fnfe) {
    // TODO
}
catch (IOException ioe) {
    // TODO
}

Also take a look at Java 7's multi-catch blocks, where unrelated Exceptions can be caught all at once with a | separator between each Exception type:

try (optionally with resources) {
    // stuff that throws FileNotFoundException and MyOwnCheckedException
}
// below exceptions are unrelated
catch (FileNotFoundException | MyOwnCheckedException e) {
    // TODO
}

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 Exceptions, but one of them is an IndexOutOfBoundsException, which is a RuntimeException (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 the List being iterated, i.e. list.size(), in order to prevent IndexOutOfBoundsException from being thrown.

I guess in this case it's just to provide an example though.

like image 145
Mena Avatar answered Aug 08 '26 11:08

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!