gpt4 book ai didi

Java - 抛出和捕获相同的方法

转载 作者:行者123 更新时间:2023-11-29 07:30:52 24 4
gpt4 key购买 nike

我无法理解现有代码。我想知道 Java 如何管理抛出异常并以相同的方法捕获它。我在其他问题中找不到它,所以我准备了示例。在 Java 中运行下面的代码会输出什么?

public static void main(String [ ] args) {
try{
System.out.println("1");
method();
}
catch(IOException e) {
System.out.println("4");
}
}

public static void method() throws IOException {
try {
System.out.println("2");
throw new IOException();
}
catch(IOException e) {
System.out.println("3");
}
}

它将是1 2 31 2 4 ?

最佳答案

好吧,让我们检查一下:

    public static void main(String [ ] args) {
try{
System.out.println("1"); //<--When your code runs it first prints 1
method(); //<--Then it will call your method here
}
catch(IOException e) { //<---Won't catch anything because you caught it already
System.out.println("4");
}
}

public static void method() throws IOException { //<--Your Signature contains a throws IOException (it could throw it or not)
try {
System.out.println("2"); //<--It will print 2 and thow an IOException
throw new IOException(); //<--now it throws it but as you're using a try catch it will catch it in this method
}
catch(IOException e) {//the exception is caught here and it so it will print 3
System.out.println("3"); //<--Prints 3
}
}

现在,如果您删除 method() 方法中的 catch 子句,它会为您捕获它:

    public static void main(String [ ] args) {
try{
System.out.println("1"); //<--When your code runs it first prints 1
method(); //<--Then it will call your method here
}
catch(IOException e) { //<---It will catch the Exception and print 4
System.out.println("4");
}
}

public static void method() throws IOException { //<--Your Signature contains a trows IOException (it could trhow it or not)
System.out.println("2"); //<--It will print 2 and thows an IOException
throw new IOException();
}

请记住,try-catch 的意思是:CATCH IT OR THROW IT(其他人会捕获它,否则它会转到 main 并停止您的进程)。

关于Java - 抛出和捕获相同的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42954910/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com