Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throw java exception and stops

I have a simple Java program with a main method and several other methods. Each method can fail with a different exception.

What I am doing now is adding a try-catch block for each method, but the problem is that if the first method fails and I catch and print the exception, the program proceeds.

I want the program to stop if any exception occurs. What is the recommended way to solve this in Java?

My current code is the following:

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();
    }
}

Every method has a different exception type. Should I use some generic exception and just throw it with the appropriate message, instead of using the try catch blocks?

like image 759
Jenny Hilton Avatar asked Jan 03 '23 13:01

Jenny Hilton


1 Answers

Your last solution, to use specific exceptions, would be more readable but could result in a lot of Exception subclass.

Here is a quick code update :

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{ ... }

Since I try to have the return statements in the beginning (filter parameter) or the end of a method (correct method execution), this design is useful. If not, we would have multiple line that could stop a process, leading to a complicated debugging.

EDIT:

Of course, if you only need to print a text and stop there (no exception management), you can simply create your own exception in each method :

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

Where e is the original Exception thrown

like image 54
AxelH Avatar answered Jan 06 '23 02:01

AxelH