Professional Documents
Culture Documents
Scope:
An Exception can be anything which interrupts the normal flow of the program. When an excep-
tion occurs program processing gets terminated and doesn’t continue further. In such cases we
get a system generated error message. The good thing about exceptions is that they can be han-
dled. Exceptions are conditions within the code. A developer can handle such conditions and
take necessary corrective actions.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is de-
rived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions normally happen in case of
severe failures, which are not handled by the java programs. Errors are generated to indicate errors gen-
erated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot re-
cover from errors. The Exception class has two main subclasses: IOException class and RuntimeExcep-
Object Oriented Programming
Faculty of Computing and Information Technology (FCIT)
Department of Computing Indus University, Karachi
tion Class.
Example 4: To demonstrate using our user-defined exception, the following CheckingAccount class con-
tains a withdraw() method that throws an InsufficientFundsException.
Example 5: The following BankDemo program demonstrates invoking the deposit() and withdraw()
methods of CheckingAccount.
Example 7: Java finally example where exception occurs and not handled.
Exercise:
1. Write a program that prompts the user to read two integers and displays their sum. Your program
should prompt the user to read the number again if the input is incorrect.