When to catch an Exception vs. When to throw an Exception?

I have been coding for some time in Java. But sometimes I don’t understand when I should throw an exception and when I should catch an exception. I am working on a project in which there are many methods. A hierarchy is something like this -

Method A will call Method B and Method B will call some Method C and Method C will call Method D and Method E.

So, currently I am doing this: I throw exceptions in all methods and catch them in method A and then register as an error.

But I'm not sure if this will be the right way? Or should I start catching exceptions in all methods. So this is why this confusion started in mine- When should I catch Exception vs, when should I throw exceptions. I know this is a stupid question, but somehow I'm trying to understand this basic concept.

Can someone give me a detailed example When to catch the Exception vs When to throw the Exceptionsso that my concepts are cleared of this? And in my case, should I continue to throw an exception and then catch it in the main call of method A?

+30
source share
7 answers

You should catch an exception when you are in a method that knows what to do.

For example, forget about how it works at the moment, let's say you write a library to open and read files.

So you have a class, say:

public class FileInputStream extends InputStream {
    public FileInputStream(String filename) { }
}

Now, let's say the file does not exist. What do you have to do? If you are struggling to come up with an answer because there is nobody ... FileInputStreamdoes not know what to do with this problem. Thus, he throws the chain, i.e.:

public class FileInputStream extends InputStream {
    public FileInputStream(String filename) throws FileNotFoundException { }
}

, - . , :

public class Main {
    public static void main(String... args) {
        String filename = "foo.txt";
        try {
            FileInputStream fs = new FileInputStream(filename);

            // The rest of the code
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find input file: " + filename);
            System.err.println("Terminating...");
            System.exit(3);
        }
    }
}

, , .

+39

, , .

- , . f ​​ , f - , f , f .

:

  • , (, ) , ;
  • , (, );
  • , , . , . - , .

.

, , , .

, , , , , .

+5

, , - . , - , D.

? , ", SERVER/DB" - . Is - A, B C, SERVER/DB (, ) ? , , . , , 1 , .

, . Swing/desktop, , (, "" ), (, "" ). "" - .

- .

, , , URL- , . ...

/*  gets called by an actionListener when user clicks a menu etc... */
public URL openTheDB() {
  URL urlForTheDB = MyCoolDialogUtils.getMeAURL(URL somePreviousOneToFillInTheStart);
  try {
     verifyDBExists(urlForTheDB);
     // this may call a bunch of deep nested calls that all can throw exceptions
     // let them trickle up to here

     // if it succeeded, return the URL
     return urlForTheDB;
  }
  catch (NoDBExeption ndbe) {
    String message = "Sorry, the DB does not exist at " + URL;
    boolean tryAgain = MyCoolDialogUtils.error(message);
    if (tryAgain)
      return openTheDB();
    else
      return null;  // user said cancel...
  }
  catch (IOException joe) {
    // maybe the network is down, aliens have landed
    // create a reasonable message and show a dialog
  }

}
+4

. , .

  • catch , (, /)
  • throw,
+3

, .

- , (, ), , sev1, "-", , , .

, . ( , - ). , , . , " " (, cron, spring ajax)

throw new RuntimeException(checked,"Could not retrieve contact " + id);

-, "" , .

, :

, - . . , .

, , .

: 1234 - :

: 1234. ... , .

: : 1234... , , , NPE ..

: : 73932...

Stack Trace: : JPA: null " "

+3

, .

, , , ,

+1

, , , , .

, , , - IOException, , load (, ..). , load, , , , .

0

Source: https://habr.com/ru/post/1607332/


All Articles