简体   繁体   中英

Exception thrown is null

I have a setup such as...

public class MyClass {
   Exception e = null;   

   try {
      Game.runItNow();
   } catch (Exception e) {
      this.e = e;
   }

   if (this.e == null) {
      showError();
   }
}

public class Game {
    public static void runItNow() throws IOException {
       try {
          HttpManager.getData()
       } catch(IOException e) {
          // here, e = null
          throw e;
       }
    }
}

public class HttpManager {    

    public static String getData() throws IOException {
       String someData = "The fox is brown";
       String someWord = "fox";

       if (someData.contains(someWord)) {
          throw new IOException();
       }

       return someData;
    }
}

The problem is, when I catch the IO exception.. e == null . Not sure if I'm having a brain fart or not, but I'm pretty confused. Why is e == null ? I am throwing a new instance of it.

If the code you have above is what you actually have then it's no wonder it isn't working. Your MyClass isn't a proper class. Either you need static blocks, a main method, or a constructor with that code in.

If you create a constructor with that code in, or a main method then it will work just fine.

public class MyClass {

   public static void main(String[] args) {
       Exception e = null;   

       try {
          Game.runItNow();
       } catch (Exception e) {
          this.e = e;
       }

       if (this.e == null) {
          showError();
       }
   }
}

您将覆盖使用新IOException生成的IOException,而没有例外。

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