How can I catch all the exceptions that will be thrown through reading and writing a file?

前端 未结 7 1362
眼角桃花
眼角桃花 2020-12-02 13:46

In Java, is there any way to get(catch) all exceptions instead of catch the exception individually?

相关标签:
7条回答
  • 2020-12-02 14:48

    While I agree it's not good style to catch a raw Exception, there are ways of handling exceptions which provide for superior logging, and the ability to handle the unexpected. Since you are in an exceptional state, you are probably more interested in getting good information than in response time, so instanceof performance shouldn't be a big hit.

    try{
        // IO code
    } catch (Exception e){
        if(e instanceof IOException){
            // handle this exception type
        } else if (e instanceof AnotherExceptionType){
            //handle this one
        } else {
            // We didn't expect this one. What could it be? Let's log it, and let it bubble up the hierarchy.
            throw e;
        }
    }
    

    However, this doesn't take into consideration the fact that IO can also throw Errors. Errors are not Exceptions. Errors are a under a different inheritance hierarchy than Exceptions, though both share the base class Throwable. Since IO can throw Errors, you may want to go so far as to catch Throwable

    try{
        // IO code
    } catch (Throwable t){
        if(t instanceof Exception){
            if(t instanceof IOException){
                // handle this exception type
            } else if (t instanceof AnotherExceptionType){
                //handle this one
            } else {
                // We didn't expect this Exception. What could it be? Let's log it, and let it bubble up the hierarchy.
            }
        } else if (t instanceof Error){
            if(t instanceof IOError){
                // handle this Error
            } else if (t instanceof AnotherError){
                //handle different Error
            } else {
                // We didn't expect this Error. What could it be? Let's log it, and let it bubble up the hierarchy.
            }
        } else {
            // This should never be reached, unless you have subclassed Throwable for your own purposes.
            throw t;
        }
    }
    
    0 讨论(0)
提交回复
热议问题