Unit1 Exception Handling
Unit1 Exception Handling
import java.util.ArrayList;
import java.util.Arrays;
// create a checked exception
class
class CustomException extends Exception
{ public CustomException(String message)
In the given example, we have extended the Exception class to create a custom exception named
{
// call the constructor of Exception class
CustomException. Here, we call the constructor of Exception class from the CustomException
super(message); class using super() keyword.
} Inside the method checkLanguage(), we have checked the exception condition, and if the
} exception occurs, the try..catch block handles the exception.
class Main {
ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java",
"Python", "JavaScript"));
// check the exception condition
public void checkLanguage(String language) throws
CustomException {
// throw exception if language already present in
ArrayList if(languages.contains(language)) {
throw new CustomException(language + " already
exists");
}
else {
// insert language to
ArrayList
languages.add(language);
System.out.println(language
+ " is added to the
ArrayList");
}
}
public static void main(String[]
args) {
// create object of Main
class Main obj = new
Main();
// exception is handled using try...catch
try {
obj.checkLanguage("Swift");
Create custom unchecked exception class
import java.util.ArrayList;
import java.util.Arrays;
// create a unchecked
exception class
class CustomException extends RuntimeException
{ public CustomException(String message) {
// call the constructor of RuntimeException
super(message);
}
} In the given example, we have extended the RuntimeException class to create an
class Main { unchecked custom exception class.
ArrayList<String> languages = new Here, you can notice that, we haven't declared any try...catch block. It is because the
ArrayList<>(Arrays.asList("Java", "Python", unchecked exception is checked at runtime.
"JavaScript"));
// check the exception condition
public void checkLanguage(String
language) {
// throw exception if language already present
in ArrayList
if(languages.contains(language)) {
throw new CustomException(language + " already
exists");
}
else {
// insert language to ArrayList
languages.add(language);
System.out.println(language + " is added to the
ArrayList");
}
}
public static void main(String[] args) {
// create object of Main class
Main obj = new Main();
// check if language already present
obj.checkLanguage("Swift");
obj.checkLanguage("Java");
}
}
Java Exception
Keywords Keyword Description
• The code which might raise exception must be enclosed within try-block
• try-block must be followed by either catch-block or finally-block, at the end
• If both present, it is still valid but the sequence of the try-catch-finally matters the most
• Otherwise, compile-time error will be thrown for invalid sequence
• The valid combination like try-catch block or try-catch-finally blocks must reside inside method
• Note: code inside try-block must always be wrapped inside curly braces, even if it contains just one line of code;
• Otherwise, compile-time error will be thrown
• Compile-time Error : “Syntax error on token “)”, Block expected after this token”
• Read more about try block in detail
catch() block
• Contains handling code for any exception raised from corresponding try-block and it must be enclosed within catch block
• catch-block takes one argument which should be of type Throwable or one of its sub-classes i.e.; class-name followed
by a variable
• Variable contains exception information for exception raised from try-block
• Note: code inside catch-block must always be wrapped inside curly braces, even if it contains just one line of code;
• Otherwise, compile-time error will be thrown
• Compile-time Error: “Syntax error on token “)”, Block expected after this token”
finally-block
Why use Java finally block?
• finally block in Java can be used to put "cleanup" code such as closing a file, closing
• finally block is used to perform clean-up connection, etc.
activities or code clean-up like closing database • The important statements to be printed can be placed in the finally block.
connection & closing streams or file resources, etc
• finally block is always associated with try-catch
block
• With finally-block, there can be 2 combinations
• One is try-block is followed by finally-block and other
is try-catch-finally sequence
• The only other possible combination is try block
followed by multiple catch block and one finally
block at the end (this is case of multiple catch blocks)
• Advantage: The beauty of finally block is that, it
is executed irrespective of whether exception is thrown
or NOT (from try-block)
• Also, it gets executed whether respective exception is
handled or NOT (inside catch-block)
• Note: finally block won’t get executed if JVM exits
with System.exit() or due to some fatal error like code
is interrupted or killed
throw clause throws keyword or throws clause
• Sometimes, programmer can also throw/raise • throws keyword is used to declare the exception that
exception explicitly at runtime on the might raise during program execution
basis of some business condition
• whenever exception might thrown from program, then
• To raise such exception explicitly during programmer doesn’t necessarily need to handle that
program execution, we need to use exception using try-catch block instead simply declare
throw keyword that exception using throws clause next to method
signature
• Syntax: • But this forces or tells the caller method to handle that
exception; but again caller can handle that exception
• throw instanceOfThrowableType using try-catch block or re-declare those exception
with throws clause
• Generally, throw keyword is used to throw
user-defined exception or custom exception • Note: use of throws clause doesn’t necessarily mean
that program will terminate normally rather it is the
• Although, it is perfectly valid to throw information to the caller to handle for normal
pre-defined exception or already defined termination
exception in Java like IOException,
NullPointerException, • Any number of exceptions can be specified using
ArithmeticException, throws clause, but they are all need to be separated by
InterruptedExcepting, commas (,)
ArrayIndexOutOfBoundsException, etc.
• throws clause is applicable for methods & constructor
try { but strictly not applicable to classes
// some valid Java statements • It is mainly used for checked exception, as unchecked
throw new RuntimeException(); exception by default propagated back to the caller (i.e.;
} up in the runtime stack)
catch(Throwable th) { • Note: It is highly recommended to use try-catch for
exception handling instead of throwing exception
// handle exception here using throws clause
// or re-throw caught exception
}
1. Whenever checked-exception (it may be pre-defined or user-defined exception)
is thrown explicitly using throw keyword, then it must be handled Unchecked Exception- Explicitly throwing exception using throw keyword
either
using try-catch block or throws clause. Therefore, we have used throws clause
to delegate the exception responsibility to caller-method package in.bench.resources.exception.handling;
2. But whenever unchecked-exception (it may be pre-defined or user-defined exception)
is thrown explicitly using throw keyword, then it is not necessary to handle. It is up public class ThrowWithUncheckedExceptionExample {
to the choice of programmer to handle it
public static void main(String[] args) {
Checked Exception
// invoking method
package in.bench.resources.exception.handling;
anotherMethod(null);
import java.io.FileNotFoundException;
}
public class ThrowAndThrowsExample { public static void anotherMethod(String str) {
// assumed that,
// we are trying to access file from remote location
// FileReader fileReader =
// new FileReader("D:/Folder/test.txt");
throw new FileNotFoundException("File is not available");
import java.io.*;
class Parent{
import java.io.*;
class Parent{
void msg()throws ArithmeticException
{ System.out.println("parent method");
}
}
public class TestExceptionChild2 extends
Parent{ void msg()throws Exception
{
System.out.println("child method");
}
public static void main(String args[])
{
Parent p = new TestExceptionChild2();
try {
p.msg();
}
catch (Exception e){}
}
}