Professional Documents
Culture Documents
4 - Exception Handling
4 - Exception Handling
DEVELOPMENT-1
Tharanga Ekanayake
BSc (Special) MIS, First Class
Exception Handling
“Exception is an abnormal condition.”
“Exception is an event that interrupts the normal flow of execution.”
“An exception (or exceptional event) is a problem that arises during the
execution of a program.”
“Exception is an error event that can happen during the execution of a
program and disrupts its normal flow.”
“An Exception is an unwanted event that interrupts the normal flow of
the program.”
Compile time vs run time errors
• Compile time vs run time
• Compile time error
• Run time error
Why an exception occurs?
• There can be several reasons that can cause a program to throw
exception. For example: Opening a non-existing file in your program,
Network connection problem, bad input data provided by user etc.
Java Exception Keywords
try
The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by
either catch or finally. It means, we can't use try block alone.
catch
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch
block alone. It can be followed by finally block later.
Finally
The "finally" block is used to execute the important code of the program. It is executed whether an exception is
handled or not.
Throw
The "throw" keyword is used to throw an exception.
Throws
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur
an exception in the method. It is always used with method signature.
Example..
Catch multiple exceptions
But!! We have more catch statements??
Java finally block
• Java finally block is a block that is used to execute important code
such as closing connection, stream etc.
• Java finally block is always executed whether exception is handled or
not.
throw
• It is possible for your program to throw an exception explicitly
throw TrrowableInstance
• Here, TrrowableInstance must be an object of type Throwable or a
subclass Throwable
• There are two ways to obtain a Throwable objects:
• Using a parameter into a catch clause
• Creating one with the new operator
Throws clause is used to declare an exception, which means it
public class test
works similar to the try-catch block.
{
void checkAge(int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible for voting");
else
System.out.println("Eligible for voting");
}