how to throw an IOException?

前端 未结 7 1708
天涯浪人
天涯浪人 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 04:56
    static void foo() throws IOException {
        throw new IOException("your message");
    }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-19 05:09

    Please try the following code:

    throw new IOException("Message");
    
    0 讨论(0)
  • 2020-12-19 05:11
    throw new IOException("Test");
    
    0 讨论(0)
  • 2020-12-19 05:12

    Maybe this helps...

    Note the cleaner way to catch exceptions in the example below - you don't need the e instanceof IOException.

    public static void foo() throws IOException {
        // some code here, when something goes wrong, you might do:
        throw new IOException("error message");
    }
    
    public static void main(String[] args) {
        try {
            foo();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
    
    0 讨论(0)
  • 2020-12-19 05:20

    I just started learning exceptions and need to catch an exception

    To throw an exception

    throw new IOException("Something happened")
    

    To catch this exception is better not use Exception because is to much generic, instead, catch the specific exception that you know how to handle:

    try {
      //code that can generate exception...
    }catch( IOException io ) {
      // I know how to handle this...
    }
    
    0 讨论(0)
提交回复
热议问题