Notes chapter 18 Exceptions runtime errors




Дата канвертавання20.04.2016
Памер37.51 Kb.
NOTES Chapter 18 - Exceptions
RUNTIME ERRORS

  1. Unexpected - debug the code

  2. Expected (Possible user error or even developer error) - handle it

Expected - code is correct and not designed to handle this type of user interaction


For example:

Trying to open a file which is not present - your code should have code in place to handle this situation


NOTE: These types of errors should not result in the program “blowing up” and displaying a cryptic error message.

Solution:




  1. Use an if statement to surround an input statement (this is how we took care of the problem in the old days.)

if (validInt(number.getText()))

processNumber(Integer.parseInt(number.getText));

else


System.out.println(“ERROR”);

Problems:



    1. Added code brings added complexity. “More error code than actual code.”

    2. Validity is checked twice (which is redundant)

First - checked by the condition statement

Second - checked by the method




  1. Use Exception Handling Code (try-catch statement)

The try clause specifies the action to perform…followed by one or more catch clauses that specify various actions to perform in the event that an error occurs while executing the code in the try clause.


try {
code we are trying to execute
} catch ( error to catch ) {
code that handles the error
}
Benefits:

  1. Basically brings a structure to error handling.

  2. Allows the statements having the error - reporting the error.

Example (see complete example TextFieldTest)


public void actionPerformed( ActionEvent event )

{

int x = Integer.parseInt(textfield.getText());



x++;

quote.setText("Total: "+x);

}
Result: in the case of an error (entering something other than an integer) the program does not report anything.
Exception handling:

public void actionPerformed( ActionEvent event )

{

try {


int x = Integer.parseInt(textfield.getText());

x++;


quote.setText("Total: "+x);

} catch ( NumberFormatException e ) {

quote.setText("NAN");

}

}


Result: An exception will generate a detailed message specifying the error.
Correct jargon: If an error occurs then the parseInt method “raises” or “throws” an exception. The catch clause “handles” or “catches” the exception.
(see example Exception)

EXCEPTIONS ARE OBJECTS


catch ( NumberFormatException e ) explained:
NumberFormatException is an exception class which represents information on errors generated by a set of classes which include: parseInt, parseDouble, etc.
e - is the identifier naming the exception class. This variable “e” can be used to refer to the object describing the exception.
System.out.println(e.getMessage());
Check out: java.lang.Exception in the API

EXCEPTION PROPAGATION

setevent method - takes string parameters
public void setEvent( String month,

String day,

String description) {

dailyEvent[Integer.parseInt(month)-1][Integer.parseInt(day)-1]

= description;

}

event-handling code that passes Strings to setEvent - yet it receives the error notification if error detected


try {

theCalendar.setEvent(

month.getText() ,

day.getText() ,

description.getText()

);

} catch ( NumberFormatException e ) {



System.out.println(

"Date entered is invalid. " +

"Enter numeric values for the month and day."

);

}



When an exception occurs, Java looks for a try-catch to handle the exception in each method along the sequence that were invoked - Java RTE will continue looking along this “chain of invocations” until it runs out or an appropriate try-catch is found. If no try-catch found then it displays one of those complex error messages.

HANDLING MULTIPLE EXCEPTIONS


Java allows multiple catch clauses which will handle different error conditions for the code which is executed within the try part.
Book example: Use a method “setEvent” which must have a proper integer and it must fit into the proper subscript range.
try {

theCalendar.setEvent(

Integer.parseInt( month.getText() ) ,

Integer.parseInt( day.getText() ),

description.getText()

);


} catch ( NumberFormatException e ) {

System.out.println(e.getMessage());

System.out.println(

"Date entered is invalid." +

"Enter numeric values for the month and day."

);

} catch ( ArrayIndexOutOfBoundsException e ) {



System.out.println("Date value is out of range.");

System.out.println("Month must fall between 1 & 12;" +

"date must fall within selected month");

}

Alternative (Dietel) Example: using a method (quotient) to do division on two numbers.


try {

number1 = Integer.parseInt( input1.getText() );

number2 = Integer.parseInt( input2.getText() );

result = quotient( number1, number2 );

output.setText( precision3.format( result ) );

}

catch ( NumberFormatException nfe ) {



JOptionPane.showMessageDialog( this,

"You must enter two integers",

"Invalid Number Format",

JOptionPane.ERROR_MESSAGE );

}

catch ( DivideByZeroException dbze ) {



JOptionPane.showMessageDialog( this, dbze.toString(),

"Attempted to Divide by Zero",

JOptionPane.ERROR_MESSAGE );

}

EXCEPTION SUBCLASSES


The Java exception classes are all derived from the superclass called “Exception”.
Inheritance is used in constructing further exception offspring:


  1. Java allows the construction of new exception subclasses. The developer must use the “extends” clause - so that it is a subclass of “Exception”.

  2. Two major types of exceptions:

    1. RuntimeException (subclass of Exception)

Subclasses of RuntimeException. Called “unchecked” exceptions. Writing a try-catch is optional for these types of errors.




    1. All others (not subclasses of RuntimeException)

Called “checked”. If this category of exception can be raised within a method then a developer is required to handle it:



  1. supply a try-catch to handle it OR

ii. explicitly declare that the exception may propagate to the method’s invoker.

If able you can allow a group of errors to be caught by a superclass:


Example:

catch ( RuntimeException e ) {


}
This example means every error within this category will cause the execution of the code found in this catch clause.
CHECKED vs. UNCHECKED EXCEPTIONS

System.in - read a line from the keyboard. Requires handling checked exceptions.


System.in.read (read a integer value - ASCII - from the keyboard)
3 Examples:

1. Method which give compilation error

2. Try-catch clause does away with error - however error is simply caught within method. The return value must be used to report back the error to the method invoker.

3. The actual method propagates the error back up to the invoker. (Unchecked exceptions does this automatically)


Called Method:

private static String readDate() throws IOException {

}

Inside the Invoker Method:


try {

System.out.println("The date is: "+readDate());

} catch ( IOException e ) {

System.out.println( "Read failed:" +

e.getMessage() );

}

This method that uses readDate must either contain a try-catch clause to handle the exception or have a “throws IOException” to propagate it up once again.



THROWING EXCEPTION
setEvent example should not be designed to throw an array exception (The good encapsulation practice is the invokers should not have to care or be concerned for design details within setEvent)
Therefore the setEvent should simply throw an exception based on the improper nature of input parameters - IllegalArgumentException - instead of ArrayIndexOutOfBoundsException.
Throws an IllegalArgumentException instead of ArrayIndexOutOfBoundsException:
public void setEvent(int month, int day, String description) {

try {


dailyEvent[month-1][day-1] = description;

} catch (ArrayIndexOutOfBoundsException e) {

throw

new IllegalArgumentException(



"Invalid Date: " + month + "/" + day

);

}



}

Throws two exceptions with different descriptions:

public void setEvent(int month, int day, String description) {

if ( month >= 0 && month <= 12) {

try {

dailyEvent[month-1][day-1] = description;



} catch (ArrayIndexOutOfBoundsException e) {

throw


new IllegalArgumentException(

"Invalid day specified: " + day

);

}

} else {



throw

new IllegalArgumentException(

"Invalid month specified: " + month

);

}



}

Throw statement - a special statement which raises an exception:


throw new IllegalArgumentException("Invalid month specified: " + month);
Throw followed by an expression describing the exception object to be raised (construction of an object representing the exception condition)

Throw statement can appear anywhere within the method.


Also possible to define your own exception class:
public class DateRangeException extends IllegalArgumentException

{

public DateRangeException( String message ) {

super( message );

}

}


База данных защищена авторским правом ©shkola.of.by 2016
звярнуцца да адміністрацыі

    Галоўная старонка