r/learnjava • u/Aeternus44 • Nov 23 '20
Why would one want to handle the exception using "throws"?
Hope you all are doing well. I'm new to Java. I just learned that one uses "throws" when one doesn't want to handle the exception in the method that it occurs in, but the caller method. My question here might be stupid, but still, I would like to know in what way it is useful to opt for handling the exception outside of the method in which it occurs.
11
u/mladensavic94 Nov 23 '20
When you re-throw an exception its because you can not (or do not want to) handle it in current context.
For example if you want to open a file, read from it some value and return it. You write a method for file reading which throws exception when file is not on given path. In your parent method you call this file reading method for some path, and if method fails its on you to decide if you are going to return null or try another path etc.
Hope this helps.
1
u/Mr_82 Nov 23 '20
This is more helpful than the other main reply, but what I don't understand is why people won't just give a simple answer as to why you do this, instead of giving examples.
Like in a thread the other day, I saw people trying to explain why NaN === NaN in JavaScript is false, trying to use reason "inside" JavaScript itself, when in reality, you have that equality evaluating to false and another one evaluating to true, for reasons that have to do with the design of the programming language itself more then anything else; having one comparison operator evaluate to false can be beneficial for writing code, depending on the context. No one ever seems to want to discuss this though.
The overall reason, simply put, for catch and throw is (at least from my understanding) to diagnose it troubleshoot where exactly things might go wrong in your code. To disambiguate what exactly may have led to an issue, in other words.
I really just don't understand why people try to give more confusing examples instead of just pointing out why things are designed the way you are. Nothing personal to you or the other person I replied to, but this seems to be a major problem in the way programming is taught.
1
5
u/darthrado Nov 23 '20
I assume you're talking about checked exceptions forcing you to either handle them or state that you're throwing them as well
It's useful when you're the one throwing the exception.
Let's say you have a service with a method:
public void doSomeBuissinessLogicForDocumentWithId(String documentId) throws InvalidDocumentIdException {
//findDocumentById from db
//if !exists throw new InvalidDocumentIdException(documentId)
//do stuff
}You need to process some document, but you need a valid id in order to do it. If for some reason you can't find a document with that Id, the only option you have is to fail and throw exception. Since it's a checked exception - the person using your method will be forced to either handle it or throw it themselves.
Now lets take a look at another very similar scenario:
public void doSomeBuissinessLogicForDocumentWithId(String documentId) throws InvalidDocumentIdException {
//findDocumentById throws InvalidDocumentIdException
//do stuff
}In this case findDocumentById is the method that throws the InvalidDocumentIdException and the Ide forces you to either handle or rethrow the exception.
You got the Id as an input argument. You have no idea where it came from so you can't really handle it and you can't continue with your buissiness logic without the document so the only option is to fail and delegate the responsibility to handle the exception to the method that called you by adding a "throws InvalidDocumentIdException".
2
u/greglturnquist Nov 23 '20
On paper, it sounds great to have methods declare their inputs, their outputs, and the exceptions they throw.
But experience shows that deliberately declaring checked exceptions in method signatures that neither generate nor handle such an exception turns into noise with little benefit.
Hence, it's become quite popular, at least for custom exceptions, to make them extend RuntimeException, and NOT require the "throws" notation. The same process happens, whether or not the exception is "checked", so exception provide the same feature. But the amount of cognitive load is reduced.
1
u/Skiamakhos Nov 23 '20
Sometimes you want the program to fail, if things that are supposed to be there aren't or whatever - if your company is working with other suppliers & it's in the spec that this API or this data is guaranteed to be available when you need it, and it's not, you want that to show as an error. You handle it gracefully in your front end so the customer isn't alarmed or anything, but in your logs you leave no doubt as to what's happened so your management can get the third party to fix their sh!t or pay compensation for breach of contract. You don't always have to cover everyone else's ass in business, and your systems will often reflect this.
1
u/ixBerry Nov 23 '20
While using Spring, or in Business applications, you might have business logic decoupled from the controller logic ( As you should ).
There might be a chance that you want the error to be handled specifically in the controller or the service layer, so you might want to "throw" the exception, knowing that there exists a functionality that the calling method can handle such an exception.
1
u/Serializedrequests Nov 24 '20 edited Nov 24 '20
Think of it this way: Sometimes you may wish to write a method that can return more than one result. A common use for this is returning an error code. If you haven't yet written code that has normal failure cases, you will soon. Unfortunately, Java does not allow methods to return more than one result, but it does have exceptions. So we use exceptions where other languages might use multiple return types.
At least, that's how I look at it.
72
u/hashcrap Nov 23 '20 edited Nov 23 '20
You can only appropriately handle an exception if you know how the program should react, if said exception is thrown.
Let's for example assume you have a method
getFilethat takes a String of a path and returns the corresponding File object. It throws an exception if the file doesn't exist.This method is used at 2 places in the program. Once when selecting a file to be read from and once when selecting a file to be written to. Now when one of these files doesn't exist, the program should print an error message, but in order to print the correct error message, you have to know which one of the two files doesn't exist. The
getFilemethod doesn't know this, it only knows the path. So it can't handle the exception itself, but throws it and let's the caller deal with it.