简体   繁体   English

当一起处理和声明异常时会发生什么?

[英]What happens when an exception is handled and declared together?

I'm sitting for the 1z0-808 exam and many questions about exception handling appear with "throws" and a "try-catch" block used together. 我正在参加1z0-808考试,关于异常处理的许多问题都与“ throws”和“ try-catch”块一起使用出现。

I would like to know how does "throws" affect the output of a "try-catch" block when they are used together. 我想知道当它们一起使用时,“抛出”如何影响“ try-catch”块的输出。

My understanding so far is that: 到目前为止,我的理解是:

  1. "try-catch" block will handle exceptions and execute any code that you define in the "catch" block. “ try-catch”块将处理异常并执行您在“ catch”块中定义的任何代码。
  2. "throws" declares an exception and will shift the exception handling responsibility up the stack. “ throws”声明一个异常,并将把异常处理责任移到堆栈上。 For example: 例如:

     public class Test{ static void test() throws Exception{ throw new Exception(); } public static void main(String[] args) throws Exception{ test(); // A stack trace is printed } } 
  3. Using "try-catch" and "throws". 使用“ try-catch”和“ throws”。 For example: 例如:

     public class Test{ static void test() throws Exception{ try{ throw new Exception(); } catch(Exception e){ System.out.println("Handling is done"); } } public static void main(String[] args) throws Exception{ test(); // Outputs: "Handling is done" } } 

    Is there any purpose or effect in using "throws" if the exception is handled by the "try-catch" block? 如果异常是由“ try-catch”块处理的,则使用“ throws”有什么目的或效果?

Is there any purpose or effect in using "throws" if the exception is handled by the "try-catch" block? 如果异常是由“ try-catch”块处理的,则使用“ throws”有什么目的或效果?

Yes it is. 是的。

I can catch a default Exception thrown from Java for ex IllegalArgumentException and I can re throw some meaningful custom exception. 我能赶上一个默认的Exception从Java抛出前IllegalArgumentException ,我可以再抛出一些有意义的自定义异常。

So it is meaningful when you re throw exception from catch block with more details. 因此,当您从catch块中抛出具有更多详细信息的异常时,这是有意义的。

public void doLogin() throws NiceUserException {
    try {
        //To Do
    } catch(IllegalArgumentException e) {
        throw new NiceUserException("Hey! You forgot to pass your username");
    }
}

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

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