简体   繁体   English

在 Java 中捕获并声明异常?

[英]Caught and declared exception in Java?

In Java, if I declare and caught an exception, can I handle the exception in a caller anyway?在 Java 中,如果我声明并捕获了异常,我是否仍然可以在调用者中处理异常? 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:您还可以将异常包装在另一个异常中,并通过将 Exception 作为 Throwable 作为 cause 参数传递来保留原始堆栈跟踪:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java:未报告的异常Exception; 必须被抓住或宣布被扔掉 - Java: Unreported exception Exception; must be caught or declared to be thrown 未报告的异常java.lang.ClassNotFoundException; 必须被抓住或宣布被抛出 - unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown 未报告的异常 ParseException; 必须被捕获或声明被抛出 -- JAVA 错误 - unreported exception ParseException; must be caught or declared to be thrown -- JAVA Error Java错误未报告的异常IOException; 必须被抓住或宣布被抛出 - Java Error unreported exception IOException; must be caught or declared to be thrown 未报告的异常java.io.FileNotFoundException; 必须被抓住或宣布被抛出 - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 未报告的异常java.io.FileNotFoundException; 必须被抓住或宣布被扔6 - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown 6 未报告的异常java.io FileNotFoundException; 必须被抓住或宣布被抛出 - unreported exception java.io FileNotFoundException; must be caught or declared to be thrown Java错误:必须捕获未声明的异常ioexception或将其声明为引发 - Java error: unreported exception ioexception must be caught or declared to be thrown 未报告的异常java.sql.SQLException;必须被抓或宣布被扔? - Unreported exception java.sql.SQLException; must be caught or declared to be thrown? 未报告的例外例外; 必须被抓住或宣布被抛出 - unreported exception Exception; must be caught or declared to be thrown
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM