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 Java Objects Harnessing the Power of Objects Exceptions

disheng wang
disheng wang
5,422 Points

Exception vs System.exit(0)

Hi, I just learned about the exception, but I am thinking what is the advantage of using Exception vs the System.exit(0).

For example:

public void fill(int num2) {
    int maxNum =  num + num2;
    if (maxNum > 15)
        throw new IllegalArgumentException("Too big!");
}

vs

public void fill(int num2) {
    int maxNum = num + num2;
    if (maxNum > 15) {
        System.out.println("Too big");
        System.exit(0);
}

}

and in the main function, not using the try keyword and implement as normal. can someone tell me the advantage of using exception thanks.

1 Answer

michaelcodes
michaelcodes
5,604 Points

Hi there, when we use System.exit the program will terminate automatically when it reaches that line. In larger and more complex programs this is rarely what we want. Suppose you were using a calculator program, and when you accidentally typed in a letter instead of a number the program just automatically closed! Not good. Instead we use the IllegalArgumentException so that later on in the code we are able to catch this. This way the program does not just unexpectedly close, but rather states an error ("Please enter a Number!"), and than lets the user try again. This is considered a better result than having the program terminate!

Good luck and happy coding!