Module 02 - Exceptions
Module 02 - Exceptions
5th Edition
Module 2
Exceptions
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Exceptions
An exception is an object that describes
an unusual or erroneous situation
Exceptions are thrown by a program,
and may be caught and handled by
another part of the program
A program can be separated into a
normal execution flow and an exception
execution flow
Exception Handling
Java has a predefined set of
exceptions and errors that can occur
during execution
A program can deal with an exception
in one of three ways:
◦ ignore it
◦ handle it where it occurs
◦ handle it an another place in the
program
The manner in which an exception is
processed is an important design
Exception Handling
Ifan exception is ignored by the
program, the program will terminate
abnormally and produce an appropriate
message
The message includes a call stack trace
that:
◦ indicates the line on which the
exception occurred
◦ shows the method call trail that lead
to the attempted execution of the
offending line
The Basics
• Method creates an exception object
– We say “throws an exception”
• Signal to program
– Unexpected has happened
• Handle the exception
– Detect and react
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Checked and Unchecked
Exceptions
• Two types of exceptions:
• Checked
o The compiler checks that you don’t ignore them
o Due to external circumstances that the programmer cannot prevent
o Majority occur when dealing with input and output
o For example, IOException
• Unchecked
o Extend the class RuntimeException or Error
o They are the usually programmer’s or user’s fault
o Examples of runtime exceptions:
NumberFormatException
IllegalArgumentException
NullPointerException
o Example of error:
OutOfMemoryError
Checked Exceptions
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The Basics
• Runtime exceptions in the Java Class Library
– ArithmeticException
– ArrayIndexOutOfBoundsException
– ClassCastException
– IllegalArgumentException
– IllegalStateException
– IndexOutOfBoundsException
– NoSuchElementException
– NullPointerException
– StringIndexOutOfBoundsException
– UnsupportedOperationException
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Java Class Exception and Error Hierarchy
FIGURE J2-1 The hierarchy of some standard exception and error classes
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
The try Statement
To handle an exception in a program, the line that throws
the exception is executed within a try block
A try block is followed by one or more catch clauses
Each catch clause has an associated exception type and
is called an exception handler
When an exception occurs, processing continues at the
first catch clause that matches the exception type
Handling an Exception
• Postpone handling: The throws clause
– If programmer not sure what action is best for a client
when an exception occurs
– Leave the handling of the exception to the method’s
client
• Method that can cause but does not handle checked
exception must declare in its header
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Handle It Now: The try-catch Blocks
try
{
< Possibly some code >
anObject.readString(. . .); // Might throw an IOException
< Possibly some more code >
}
catch (IOException e)
{
< Code to react to the exception, probably including the following statement: >
System.out.println(e.getMessage());
}
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Multiple catch Blocks
catch (FileNotFoundException e)
{
. . .
}
catch (IOException e) // Handle all other IOExceptions
{
. . .
}
1
}
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Throwing an Exception
• If you can resolve unusual situation in a reasonable
manner
– likely can use a decision statement
• If several resolutions to abnormal occurrence possible,
and you want client to choose
– Throw a checked exception
• If a programmer makes a coding mistake by using your
method incorrectly
– Throw a runtime exception
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Designing Your Own Exception
Types
• You can design your own exception types —
subclasses of Exception or RuntimeException
• Extend RuntimeException or one of its subclasses
• Supply two constructors
1. Default constructor
2. A constructor that accepts a message string describing
reason for exception
Extracts withdraw
amount and account
number from user int withdraw(acct, amt)
{
Displays new int withdraw(amt)
balance to user {
}
}
try {
Extracts withdraw
amount and account
int withdraw(acct, amt) throws IFE
number from user
{
Displays new int withdraw(amt) throws IFE
balance to user {
if amt > balance
} throw IFE;
catch (IFE) no catch for IFE
} no catch for IFE
}
// < Other methods not relevant to this discussion are here. >
} // end OurMath
LISTING JI3-2 The class OurMath and its static method squareRoot
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Programmer-Defined Exception Classes
/** A demonstration of a runtime exception using the class OurMath. */
public class OurMathDriver
{
public static void main(String[] args)
{
System.out.print("The square root of 9 is ");
System.out.println(OurMath.squareRoot(9.0));
Program Output
The square root of 9 is 3.0
The square root of -9 is Exception in thread "main" SquareRootException:
Attempted square root of a negative number.
at OurMath.squareRoot(OurMath.java:14)
at OurMathDriver.main(OurMathDriver.java:12)
return result;
} // end squareRoot
// < Other methods not relevant to this discussion could be here. >
} // end JoeMath
Copyright © 2019, 2015, 2012 Pearson Education, Inc. All Rights Reserved
Inheritance and Exceptions
public class Driver
{
public static void main(String[] args)
{
SuperClass superObject = new SubClass();
try
{
superObject.someMethod();
}
catch (Exception1 e)
{
System.out.println(e.getMessage());
}
} // end main
} // end Driver
} // end someMethod
} // end SubClass