L7 Exception Handling
L7 Exception Handling
L7 Exception Handling
Lecture Objectives
• To understand Exception
• try/catch block
Errors
Errors
Examples of Logical
Errors
Avg=5+7+9/3;
The value of Avg will be 15 which is
wrong average. The right average
value is 7.
Exceptions
Exceptions is the
main class we use
for Exception
Handling
Exception Types
Exception Handling
Exceptional Handling is the process of
responding/handling to the occurrence of
Exceptions during the execution of
program so the remaining code can be
executed without terminating the program.
• Instead of programming for success
x.doSomething()
1. Hit the Exception and Throw it – find where an exception can occur, create an
object of exception and throw it
2. Catch the Exception and Handle it – Catch the object of exception and perform
an appropriate action to handle the exception
catch(Arithmetic Exception e)
{
…
}
Example
try {
String filename = . . .;
FileReader reader = new FileReader(filename);
Scanner in = new Scanner(reader);
String input = in.next();
int value = Integer.parseInt(input);
. . .
}
catch (IOException exception) {
exception.printStackTrace();
}
catch (NumberFormatException exception) {
System.out.println("Input was not a number");
}
Use of throw keyword
System.out.println(“k = “+k);
}
catch(ArithmeticException e) {
System.out.println(“Arithmetic Exception”);
}
System.out.println(“Hello…”);
}
}
Use of throw keyword for a customized Exception
throw exceptionObject;
Example:
throw new ArithmeticException();
Purpose:
To throw an exception and transfer control to a handler for this
exception type
Checked and Unchecked Exceptions
• Unchecked:
• Unchecked Exceptions are the exceptions which are not required to be handled at
compile time.
• All classes that direct/indirect subclasses of RuntimeException are unchecked
exceptions.
• These exceptions are caused by defects in programs code so they are programmer’s
faults.
• For example, IllegalArgumentException
Checked and Unchecked Exceptions (Cont’d)
• Two choices:
• Handle the exception
• Tell compiler that you want method to be terminated when the exception
occurs
• Use throws specifier so method can throw a checked exception
accessSpecifier returnType
methodName(parameterType parameterName, . . .)
throws ExceptionClass, ExceptionClass, . . .
Example:
public static void main(String args[]) throws IOException
Purpose:
To indicate the checked exceptions that this method can throw