05 Handout 1
05 Handout 1
Exception Handling
Basic Exception Handling
• An exception is an event that occurs during the execution of a program that disrupts the normal flow
of instructions.
• Exception handling is the process used to change the normal flow of code execution if a specified
exception occurs.
• Exceptions that occur during compilation are called checked exceptions.
Exception Description
ClassNotFoundException The class is not found.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or an interface.
NoSuchMethodException A requested method does not exist.
• Unchecked exceptions are exceptions that occur during execution. These are also known as runtime
exceptions.
Exception Description
ArithmeticException Arithmetic error, such as an integer divided by 0
ArrayIndexOutOfBoundsException Accessing an invalid index of the array
ArrayStoreException Assigning a value to an array index that does not match
the expected data type
InputMismatchException Entering a value that does not match the expected data
type
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric format
StringIndexOutOfBoundsException Accessing an invalid index (character) of a string
• The getMessage() method can be used to determine Java’s message about the exception.
Syntax: System.out.println(exceptionName.getMessage());
• Only one (1) try block is accepted in a program but there can be multiple catch blocks.
User-Defined Exceptions
• A user-defined exception is created by extending the Exception class.
• A throw statement sends an exception out of a block or a method so it can be handled elsewhere.
Output:
References:
Baesens, B., Backiel, A. & Broucke, S. (2015). Beginning java programming: The object-oriented approach.
Indiana: John Wiley & Sons, Inc.
Farrell, J. (2014). Java programming, 7th edition. Boston: Course Technology, Cengage Learning
Savitch, W. (2014). Java: An introduction to problem solving and programming, 7th edition. California: Pearson
Education, Inc.