Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

whats the difference between try...catch and if...throw when dealing with exception?

whats the difference between try...catch and if...throw when dealing with exception?

I am confused....

1 Answer

Great question.

It's probably better to take a specific example.

Suppose you have a program that needs to read a file. There's always the possibility that the file won't be where it's supposed to be.

So if you have code like this:

Scanner input = new Scanner(new File('someFile.txt');

the program won't compile unless you do something. The compiler will report an unreported exception: FileNotFoundException. The compiler "knows" that if the file doesn't exist it won't have a file to read from. So it complains.

In this case, because a file I/O error is what is known as a checked exception -- an exception that must be either caught or declared in the method header that might generate it -- you must deal with it. As the definition says, you can either (1) catch it, or (2) declare it in the appropriate method header.

For option (1), you use try... catch...

For option (2), you include a throws clause in the method header, viz.., throws FileNotFoundException, and by doing that you pass the problem on and you don't need the try... catch...

So you can do this:

public .... methodName() throws FileNotFoundException {
    . . . 
    Scanner input = new Scanner(new File('someFile.txt');
    . . .
}

or this:

```java
public .... methodName() {
    try {
        Scanner input = new Scanner(new File('someFile.txt');
    } catch (FileNotFoundException e) { 
        . . .
    }

There are many other considerations, including unchecked expressions, and other varieties of try... catch.... syntax, who deals with the thrown exception, etc., but this is the basics.