CVGalleryGamesPreviewRandomJavaSiteWeb
Site updates
Testing New System now...

Making Your Own Exceptions

To define your own exceptions, you first need to make a class for your error. It will look something like this:

public class VeryBadException extends Exception
{

    public VeryBadException()
    {
    }

    public VeryBadException(String message)
    {
	super(message);
    }

}

Obviously, you would replace VeryBadException with the actual name of your exception. It is a very good idea to end the name in Exception, so it's clear what the class is for, without having to open the source file. Calling it something like ArrayBad isn't as clear.

You can then use the exception in the same way you would a normal one. When you're defining the method, don't forget to add the throws to the declaration:

public boolean doSomething(int niceNumber) throws VeryBadException
    {
        if(niceNumber < 0)      enter your own error message ↓
            throw new VeryBadException("Numbers below 0 are not nice");   
        else      
        rest of method
    

And when you're calling the method, in this case doSomething, then you need to put code that could cause an exception in a try...catch block:

try
    {
		      doSomething(-4)
    }
catch(VeryBadException dave)
    {
		      System.out.println(dave);
	   }

If you are catching several exceptions, and there is some code that needs executing at the end of ecah one, remember to put it in a finally clause at the end.

Code examples: To see the example run, put all three classes in one folder, and run UseBox. The file StuffBox has the method that throws the exception, and the file StuffBoxException defines the exception.

Download StuffBox.java
Download StuffBox.class

Download StuffBoxException.java
Download StuffBoxException.class

Download UseBox.java
Download UseBox.class
NOTE: The Java section is mostly in maintenence mode. I don't have time to work on it right now. Errors will be corrected if pointed out, but they are not actively being searched for. Newer site features, like alternate stylesheets, may cause problems with these pages.