Practice pieces


Exceptions

This task shows something of the advantages of using accessor and mutator methods to control access and check whether releasing or adjusting variables is appropriate.


Hints:

First off, get a Point class and a class that uses it. Give the Point class an x instance variable and a setX() method. Make sure you can set x.

Next, make your own Exception class that extends the generic java.lang.Exception class. Make sure your class has a method you can use, like print() which does a System.out.println() -- something you can call in your main class' catch block to test the exception has been thrown.

Finally, add an if-statement to your setX() method that uses the throw keyword to throw new YourException(); when x > 100. You'll also need to add the throws declaration to your setX() method declaration.

Now try compiling and running -- you should see the compiler protest that you haven't caught your exception. Add a try-catch block and recompile.

If you need more help, here's the answers (or one option, anyhow).