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

前端 未结 7 1360
眼角桃花
眼角桃花 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:25

    Catch the base exception 'Exception'

       try { 
             //some code
       } catch (Exception e) {
            //catches exception and all subclasses 
       }
    
    0 讨论(0)
  • 2020-12-02 14:26

    It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.

    For most file operations, IOException is the root exception. Better to catch that, instead.

    0 讨论(0)
  • 2020-12-02 14:28

    If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

    The code looks like:

    public void someMethode() throws SomeCheckedException {
    
        //  code
    
    }
    

    Then later you can deal with the exceptions if you don't wanna deal with them in that method.

    To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

    try {
    
        // exceptional block of code ...
    
        // ...
    
    } catch (Exception e){
    
        // Deal with e as you please.
        //e may be any type of exception at all.
    
    }
    

    The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

    If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

    try{    
    }catch(MyOwnException me){
    }catch(Exception e){
    }
    
    0 讨论(0)
  • 2020-12-02 14:32

    Yes there is.

    try
    {
        //Read/write file
    }catch(Exception ex)
    {
        //catches all exceptions extended from Exception (which is everything)
    }
    
    0 讨论(0)
  • 2020-12-02 14:36

    You may catch multiple exceptions in single catch block.

    try{
      // somecode throwing multiple exceptions;
    } catch (Exception1 | Exception2 | Exception3 exception){
      // handle exception.
    } 
    
    0 讨论(0)
  • 2020-12-02 14:41

    Do you mean catch an Exception of any type that is thrown, as opposed to just specific Exceptions?

    If so:

    try {
       //...file IO...
    } catch(Exception e) {
       //...do stuff with e, such as check its type or log it...
    }
    
    0 讨论(0)
提交回复
热议问题