简体   繁体   中英

Java unhandled Exception

I'm currently developing an Android app using Android Studio and I encountered an error that I can't understand. Here's an example of my code :

public class MyClass {

    public void method1() throws MyException {
        methodIO();     // Unhandled Exception: java.io.IOException
        methodRun();    // OK
    }

    public void method2() throws Exception {
        methodIO();     // OK
        methodRun();    // OK
    }

    public void methodIO() throws IOException {}

    public void methodRun() throws RuntimeException {}
}

class MyException extends Exception {

    public MyException(){super();}

    public MyException(String message, int errorCode) {
        super(message);
    }
}

I can't figure out why in method1(), I have the following error "Unhandled Exception: java.io.IOException" while method2() compiles fine. The issue doesn't appear with a method throwing a RuntimeException even if both classes are inheritd from Exception. Does someone know what's going on here ?

Ps : I'd like to avoid using a try/catch bloc or adding a new throws clause

MyException doesn't extend IOException , so the IOException thrown by methodIO isn't handled currently.

It works in method2 because Exception is a common superclass of IOException and MyException , so it specifies how both types of exception should be handled.

Add it to the throws clause of method1 :

public void method1() throws MyException, IOException {

or catch in the method body:

public void method1() throws MyException {
  try {
    methodIO();
  } catch (IOException e) {
    // Handle appropriately.
  }
}

method2() has a throws declaration for the base type Exception , of which IOException is a derived type; whereas method1() throws a MyException , which IOException does not derive from. Add IOException to the throws declaration of method1() :

public void method1() throws MyException, IOException {
    methodIO(); 
}

or you could always catch the IOException and throw a MyException instead:

public void method1() throws MyException {
    try {
        methodIO(); 
    } catch (IOException e) {
        throw new MyException();//construct MyException however; this is just an example
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM