Java Try Catch block

前端 未结 2 568
庸人自扰
庸人自扰 2021-01-21 03:29

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 fo

2条回答
  •  Happy的楠姐
    2021-01-21 04:18

    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.

提交回复
热议问题