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
try, catch, and finally
• A try block is a block of code that might throw an exception that can be handled by a matching catch
block.
• A catch block is a segment of code that can handle an exception that might be thrown by the try block
that precedes it.
• 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.
• A user-defined exception is created by extending the Exception class.
• The finally block contains statements which are executed whether or not an exception is thrown.
There can only be one (1) finally block after a try-catch structure but it is not required.
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: