Exception Objects

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page        

Answer:

exp refers to an object of class Exception (or a subclass).

Exception Objects

Here is an outline of the try/catch structure:

try
{
  // statements, some of which might throw an exception
}

catch ( SomeExceptionType ex )      // may be omitted if there is a finally block
{
  // statements to handle 
  // SomeExceptionType exceptions
}

// additional catch blocks (optional)

// finally block  (optional, unless there are no catch blocks)

When a catch{} block receives control it has a reference to an object of class Exception (or a subclass of Exception). The class of the object depends on what exception was thrown.

When an exception event occurs while a program is running, the Java run time system takes over and creates an Exception object to represent the event. Information about the event is put in the object. If the exception arose inside a try{} block, the Java run time system sends the Exception object to the appropriate catch{} block (if there is one).

Exception objects are Java objects. They have member data and member methods, including:

  • public void printStackTrace()
    • Print a stack trace ― a list that shows the sequence of method calls up to this exception.

  • public String getMessage()
    • Return a string that may describe what went wrong.

A catch{} block can use these methods to write an informative error message to the monitor.

QUESTION 2:

Say that an array has been declared by:

int[] value = new int[10];

Is it legal to refer to value[10] ?