Chapter 05_Interface and Exception Handling
Chapter 05_Interface and Exception Handling
Exception Handling
1
Exceptions
• An exception is an event that occurs during the execution of a program that
disrupts the normal flow of instructions.
• An exception can occur for many different reasons. Following are some
scenarios where an exception occurs.
– A user has entered an invalid data.
– A file that needs to be opened cannot be found.
– A network connection has been lost in the middle of communications or the JVM has run
out of memory.
• Some of these exceptions are caused by user error, others by programmer error,
2
and others by physical resources that have failed in some manner.
Exception Handling
• Exception Handling is a mechanism to handle runtime errors.
• It helps to continue the program execution with the exception of the remaining code,
then try to catch the exception object thrown by the error condition and then display
appropriate message for taking corrective actions.
• The core advantage of exception handling is to maintain the normal flow of the
application
• Types of Java Exceptions
– Checked Exception
3
– Un-Checked Exception
Java Exception Keywords
Keyword Description
The "try" keyword is used to specify a block where we should place exception
try code. The try block must be followed by either catch or finally. It means, we
can't use try block alone.
The "catch" block is used to handle the exception. It must be preceded by try
catch block which means we can't use catch block alone. It can be followed by
finally block later.
The "finally" block is used to execute the important code of the program. It is
finally
executed whether an exception is handled or not.
throws exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
public class JavaExceptionExample{ Example
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}
catch(ArithmeticException e){ Output:
System.out.println(e); java.lang.ArithmeticException: / by zero
} rest of the code...
//rest code of the program
System.out.println("rest of the code...");
}
} 5
Common Scenarios of Java Exceptions
• A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
a[10]=50; //ArrayIndexOutOfBoundsException
Chapter 06