pnv
pnv

Reputation: 1499

Exceptions in Java: Using throws or try-catch

This is a very well discussed topic. Out of many links, I did find the below two useful.

1, 2

My questions is this:

  1. I am writing multiple methods, some for general purposes- say, writing into file, reading from file, splitting a string using some regex.

  2. I am calling these methods from different parts of my application- say class1, class 2 and class 3 calls the file writing method, but with different file names and data.

Where should I include try catch and throws? 1. The outermost method, say the main, from where I am calling the class1, class2 and class 3 methdods have one set of try, catch and use throws in the innermost functions.

  1. Or, have a try catch in the innermost-None to the outer files..

Which is a better option and why? Are there any other ways of dealing with this.

Thanks

Upvotes: 0

Views: 333

Answers (1)

Rudi Kershaw
Rudi Kershaw

Reputation: 13012

The heart of this matter is how to decide logically where your exceptions need to be handled.

Let's take an example. A method that takes a File object and performs some operation.

public void performFileOperation(File f) throws FileNotFoundException{
    // Perform logic.
}

In this case, chances are that you want the class/method calling this method to handle the Exception. If you had a try/catch block in the performFileOperation() method, then the method calling the performFileOperation() method would never know if the operation failed (and therefore can't know what to do about it).

It is really a matter of where it makes sense to handle the Exception that is thrown. You need to work out which sections of your code need to know that an exception has occurred, and use try/catch blocks there. If the next level up needs to know as well, then the catch block can throw the Exception so the method further up the stack can know about and handle it as well.

Another good way to look at it is that most exceptions need to be handled. Something needs to be done about them. If your method is not in a position to do something significant to handle that exception then it needs to throw the Exception until it makes it's way to somewhere that can meaningfully handle (read, do something about) it.

I hope this helps.

Upvotes: 2

Related Questions