抛出Java异常并停止程序。

4

我有一个简单的 Java 程序,其中包含一个 main 方法和几个其他方法。每个方法都可能出现不同的异常。

目前我正在为每个方法添加一个 try-catch 块,但问题是如果第一个方法失败并且我捕获并打印了异常,则程序会继续运行。

我希望程序在出现任何异常时停止。在 Java 中,推荐的解决方法是什么?

我的当前代码如下:

public static void main(String[] args) {
    // Get File Path
    String filePath = null;
    try {
        filePath = getFilePath(args);
    } catch (FileNotFoundException e) {
        System.out.println("not found");
    }

    // Load File content
    AtomicReference<String> content = new AtomicReference<String>();
    try {
        content.set(readYamlFile(sourceFilePath));
    } catch (IOException e) {
        System.out.println("Not able to load file");
    }


    try {
        jsonStr = convert(content.toString());
    } catch (IOException e) {
        System.out.println("Conversion failed ");
        e.printStackTrace();
    }
}

每种方法都有不同的异常类型。我应该使用一些通用的异常,并只是带有适当的消息抛出它,而不是使用try catch块吗?


即使使用自定义异常,您仍然需要try-catch块。但是抛出IOException有什么问题呢? - OneCricketeer
5个回答

3

如果发生异常,我想停止执行

您可以在catch块中放置return;System.exit(1)throw e;。每个都会停止执行。

取决于您的需求,但您可以使用一个try块,后跟多个catch块。


System.exit的参数值不应该是-1吗? - Chlebik
在处理异常的情况下,当然意味着程序以错误的方式结束。 - Chlebik
我的提到的方法只是停止执行。我不明白你在问什么。 - OneCricketeer

3

你提出的最后一个解决方案是使用特定的异常,这将会让代码更易读,但可能会导致大量的异常子类。

这里是一个快速的代码更新:

public static void main(String[] args) {
    try {
        String filePath = getFilePath(args);
        AtomicReference<String> content = new AtomicReference<String>();
        content.set(readYamlFile(sourceFilePath));
        jsonStr = convert(content.toString());
    }  catch (FileNotFoundException e) {
        System.out.println("not found");
    } catch (ReadYamlFileException e) {
        System.out.println("Not able to load file");
    } catch (ConvertJsonExceptione) {
        System.out.println("Conversion failed ");
    }
}

private String readYamlFile(String) throws ReadYamlFileException{ ... }
private String convert(String) throws ConvertJsonException{ ... }

由于我尝试将 return 语句放在方法的开头(过滤参数)或结尾(正确执行方法),因此这种设计很有用。否则,我们将会有多行代码可能会停止进程,导致繁琐的调试。

编辑:

当然,如果你只需要打印文本并停在那里(没有异常管理),你可以在每个方法中简单地创建自己的异常:

private String readYamlFile(String) throws IOException {
    try{
       ...
    } catch (IOException e) {
        throw new IOException("Not able to load file", e);
    }
}

其中e是原始抛出的Exception


2
你可以在主方法中处理异常,该方法调用其他方法。为不同捕获的异常创建多个catch,打印特定的消息并再次从主函数抛出已捕获的异常。
public class Test {

public static void main(String args[]){

        System.out.println("Executing main method ");
    try{
        Test t = new Test();            //create an object
        t.method1();                    //call method 1
        t.method2();                    //call method 2
        t.method3();                    //call method 3

    }catch(NullPointerException npe){
        System.out.println("NullPointer Exception occured");
        throw npe;
    }catch(ArithmeticException ae){
        System.out.println("Arithmetic Exception occured");
        throw ae;
    }catch(ArrayIndexOutOfBoundsException aie){
        System.out.println("ArrayIndexOutOfBounds Exception  occured");
        throw aie;
    }catch(Exception e ){
        System.out.println("Some exception occured");
        throw e;
    }

 // will not be executed as exception is thrown above in catch block
        System.out.println("Exiting main method ");  

}



private void method1() {
        System.out.println("Executing method 1 ");

        String nullString = null;
        nullString.length();


}


private void method2(){
    System.out.println("Executing method 2 ");

    int i= 100/0;

}


private void method3(){

    System.out.println("Executing method 3 ");

    int[] myArray = new int[5];

    myArray[7]= 0;

    }


}

关键点1:如果异常发生在第一个方法中,那么其余的方法/代码将不会执行。

关键点2:您仍然可以在主函数中处理异常并打印消息。

    *Output from above code:*

    Executing main method 
    Executing method 1 
    Exception in thread "main" java.lang.NullPointerException
    NullPointer Exception occured
        at Test.method1(Test.java:38)
        at Test.main(Test.java:9)

其他选项:

  1. Catch the exception in the called method itself, print the msg and exit the program using System.exit(1).

    private void method1() {
        System.out.println("Executing method 1 ");
    
    try{
        String nullString = null;
        nullString.length();
    }catch(Exception e){
        System.out.println("Null pointer exception in method 1");
        System.exit(1);
    }
    
    }
    

你在这个概念中隐藏了一个问题,有两个try-catch捕获了IOException并记录不同的消息。你将无法在你的“独特的try-catch”中区分它们。 - AxelH

1
  1. 重构您的代码以使用try with resources
  2. try/catch块的数量取决于您的应用程序设计。但是,如果您知道如何处理它们并将其他异常抛给父方法,则应在子方法中处理所有异常。

我在这里没有看到任何“Closable”实现,那么为什么要使用“try-with-resources”? - AxelH
他在这里读取文件,因此在其下方使用资源。最好不要抛出 IOExceptionFileNotFoundException 等异常,而是在 try-with-resources 中处理它,并仅在需要时抛出 CustomBuisnessException - Mike Adamenko
好的,资源在方法中,而不是这里。所以这是/可能是正确的。在某些情况下,重新抛出异常比返回null更好(即使我自己没有完全遵循建议;))。 - AxelH

1
您可以通过以下方式停止代码执行:

1 停止当前线程并返回

Thread.currentThread().interrupt();
return;

通过调用 System.exit(1) 来退出程序

在无返回值方法中使用 return

抛出异常 throw e


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接