简体   繁体   中英

Caught and declared exception in Java?

In Java, if I declare and caught an exception, can I handle the exception in a caller anyway? Or it needs not to be caught to handle it by caller?

class A {
  void first() throws Exception { 
    try {
      throw new Exception("my exception")
    } catch (Exception e) {
      log.message("Error in first()", e.getCouse)
      throw e
    }
  }
}

class B {
  Result second(A a) {
    try {
      a.first()
    } catch (Exception e) {
      log.message("Caught in B class", e.message)
      return new Result(result: null, error: e.message)
    }
  }

  second(A a)
}

You can simply rethrow the exception you've caught (obviously the surrounding method has to permit this via its signature etc.). The exception will maintain the original stack trace.

catch (WhateverException e) {
    throw e;
}

You can also wrap the exception in another one AND keep the original stack trace by passing in the Exception as a Throwable as the cause parameter:

try
{
   ...
}
catch (Exception e)
{
     throw new YourOwnException(e);
}

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