how to throw an IOException?

前端 未结 7 1749
天涯浪人
天涯浪人 2020-12-19 04:17
public class ThrowException {
    public static void main(String[] args) {
        try {
            foo();
        }
        catch(Exception e) {
             if (e         


        
7条回答
  •  半阙折子戏
    2020-12-19 05:05

    If the goal is to throw the exception from the foo() method, you need to declare it as follows:

    public void foo() throws IOException{
        //do stuff
        throw new IOException("message");
    }
    

    Then in your main:

    public static void main(String[] args){
        try{
            foo();
        } catch (IOException e){
            System.out.println("Completed!");
        }
    }
    

    Note that, unless foo is declared to throw an IOException, attempting to catch one will result in a compiler error. Coding it using a catch (Exception e) and an instanceof will prevent the compiler error, but is unnecessary.

提交回复
热议问题