r/learnjava • • 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.

58 Upvotes

16 comments sorted by

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 getFile that 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 getFile method 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.

13

u/TiltedBlock Nov 23 '20

That’s a great explanation, the example is perfect!

2

u/Dokiace Nov 23 '20

The getFile method doesn't know this, it only knows the path.

but can we tell which one caused the error if we log the error from the getFile method?

4

u/hashcrap Nov 23 '20

We know which one it is at the call sites of getFile, because that is point in the program where I'm actually doing the reading from / writing to the file.

If we log the exception from getFile directly to a logFile to evaluate later on, we could only log the path of the file that caused the error, but not if this was supposed to be the read or the write file.

That's why we would not do anything with the exception in getFile except throwing it. We simply do not have enough information to appropriately handle it.

1

u/Dokiace Nov 24 '20

but not if this was supposed to be the read or the write file.

ah I see, I get it now! thanks!

-1

u/Mr_82 Nov 23 '20

Why are you talking about two files though? There should be only file to be concerned about here, from what you've written. You've said this method just takes a String and tries to match it to a file. So there's a string, and the file that string is meant to pair with, but that should be all we're concerned with here, for this example.

I'd need to hear an explanation for that first, and I generally do know the difference/meaning of writing and reading in programming, but where exactly is anything being "written to" here?

(I understand this concept in general, and mean no offense, but I really don't understand why people seem to try and make learning programming more difficult than it is.)

5

u/Hour-Positive Nov 24 '20

He gives an example of a method that throws an exception, that method is used in TWO different places. Hence it makes sense that the exception is handled by the caller.

Don't pad a comment or question with noise

1

u/hashcrap Nov 24 '20

You are right, the getFile method is only concerned with one file at a time. However the program consists of more than just the getFile method. The example is supposed to be a program that reads stuff from one file and writes it to another file.

If the read-file doesn't exist, it should print"Can't find read file"

If the write-file doesn't exist, it should print "Can't find write file"

That means whichever function handles the exception and prints the error message, has to know if the path that caused the exception belongs to the read- or the write-file. The getFile method doesn't know this. So we handle the exception somewhere else.

I don't see where my explanation is making things more difficult than they need to be, I tried to be as clear as possible. But I hope this now clears things up.

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

u/Hour-Positive Nov 24 '20

Your understanding is wrong.

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.