0% found this document useful (0 votes)
1 views

Unit1 Exception Handling

Uploaded by

Swastik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Unit1 Exception Handling

Uploaded by

Swastik Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

EXCEPTION HANDLING

The Exception Handling in Java is one of the powerful


mechanism to handle the runtime errors so that the
normal flow of the application can be maintained. In
Java, an exception is an event that disrupts the normal
flow of the program. It is an object which is thrown at
runtime. Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

Difference between Checked and Unchecked


Exceptions
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException,
SQLException, etc. Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions.
For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
Java program to create custom checked exception

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

try The "try" keyword is used to specify a block where we should


place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be


Java provides five keywords preceded by try block which means we can't use catch block
that are used to handle the alone. It can be followed by finally block later.
exception. The following finally The "finally" block is used to execute the necessary code of the
table describes each. 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 specifies
that there may occur an exception in the method. It doesn't throw
an exception. It is always used with method signature.
try block()

• 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) {

public static void main(String[] args) if(str == null){


throws FileNotFoundException { throw new NullPointerException("Please send some valid String");
}
// must be surrounded with try-catch block compulsorily,
// because we are invoking method throwing // further processing with the string value
// checked-exception OR throws clause }
printFileContent(); }
}

// throwing checked exception


public static void printFileContent()
throws FileNotFoundException {

// 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");

// further file processing


}
}
CUSTOMIZED / USER-DEFINED EXCEPTIONS // class representing custom exception
class InvalidAgeException extends Exception
In Java, we can create our own exceptions that are derived {
classes of the Exception class. Creating our own Exception is public InvalidAgeException (String str)
known as custom exception or user-defined exception. Basically, {
Java custom exceptions are used to customize the exception // calling the constructor of parent Exception
according to user need. super(str);
}
Why use custom exceptions?
}
Java exceptions cover almost all the general type of exceptions // class that uses custom exception InvalidAgeException
that may occur in the programming. However, we sometimes public class TestCustomException1
need to create custom exceptions. {
// method to check the age
Following are few of the reasons to use custom exceptions: static void validate (int age) throws InvalidAgeException{
if(age < 18){
1. To catch and provide specific treatment to a subset of // throw an object of user defined exception
existing Java exceptions. throw new InvalidAgeException("age is not valid to vote");
Example of Java custom exception. In the code, constructor of
2. Business logic exceptions: These are the exceptions related InvalidAgeException takes a string as an argument. This
to business logic and workflow. It is useful for the }
else { string is passed to constructor of parent class Exception using
application users or the developers to understand the exact the super() method. Also the constructor of Exception class
problem. System.out.println("welcome to vote");
} can be called without using a parameter and calling super()
3. In order to create custom exception, we need to extend } method is not mandatory.
Exception class that belongs to java.lang package. // main method
public static void main(String args[])
{ Consider the following example, where we create a
try custom exception named WrongFileNameException:
Steps to Create a Custom Exception in Java {
1.Create your own Exception Class named // calling the method public class WrongFileNameException extends Exception
validate(13);
InvalidAgeException that extends Exception {
}
Class from java.lang. catch
public WrongFileNameException(String errorMessage)
2. Create a Constructor Method with (InvalidAgeException {
String statement as an argument. String as ex) super(errorMessage);
{ }
an argument allows us to custom
System.out.println(" }
message each time we throw an exception. Caught the
3. Call super(statement) i.e. Constructor method of a exception");
superclass with a statement as input. This will // printing the message from InvalidAgeException object
print our custom message with the System.out.println("Exception occured: " + ex);
exception. }
System.out.println("rest of the code...");
Usage of Java finally Case 2: When an exception occurr but not handled by the Case 3: When an exception occurs and is handled by the
Let's see the different cases where Java finally block catch block catch block
can be used. Let's see the the following example. Here, the code throws an
exception however the catch block cannot handle it. Despite Example:
this, the finally block is executed after the try block and then Let's see the following example where the Java code throws
Case 1: When an exception does not occur the program terminates abnormally. an exception and the catch block handles the exception. Later
Let's see the below example where the Java program does the finally block is executed after the try-catch
not throw any exception, and the finally block is executed public class TestFinallyBlock1{ block. Further, the rest of the code is also executed normally.
after the try block. public static void main(String args[])
class TestFinallyBlock { public class TestFinallyBlock2{
{
public static void main(String args[]){
try { public static void main(String args[])
try{
System.out.println("Inside the try block"); {
//below code do not throw any exception
//below code throws divide by zero exception try {
int data=25/5;
System.out.println(data); int data=25/0; System.out.println("Inside try block");
} System.out.println(data); //below code throws divide by zero exception
//catch won't be executed } int data=25/0;
catch(NullPointerException e) //cannot handle System.out.println(data);
{ System.out.println(e); Arithmetic type }
} exception //handles the Arithmetic Exception / by zero
//executed regardless of exception occurred or not //can only accept Null Pointer type exception Divide exception
finally { catch(NullPointerException e) catch(ArithmeticException e)
System.out.println("finally block is always { System.out.println(e); { System.out.println("Exception
executed"); } handled"); System.out.println(e);
} //executes regardless of exception occured or }
not //executes regardless of exception occured or
System.out.println("rest of phe code..."); finally not finally {
} { System.out.println("finally block is always executed");
} System.out.println("finally block is always }
executed"); System.out.println("rest of the code...");
} }
System.out.println("rest of the code..."); }
}
}
Exception Handling with Method Overriding in
There
Java are many rules if we talk about method overriding with exception
handling. Some of the rules are listed below:
1. If the superclass method does not declare an exception
• If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but it can declare unchecked exception.
2. If the superclass method declares an exception
• If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
Rule-1: If the superclass method does not declare an exception- If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception.

import java.io.*;
class Parent{

// defining the method


void msg() {
System.out.println("
parent method");
}
}
public class
TestExceptionChild
extends Parent
{
// overriding the
method in child class
// gives compile time
error
void msg() throws IOException
{ System.out.println("TestExceptionChild"
);
}
public static void main(String args[])
{
Parent p = new TestExceptionChild();
Rule 2:If the superclass method declares an exception- If the superclass method declares an exception, subclass overridden
method can declare the same subclass exception or no exception but cannot declare parent exception.

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){}
}
}

You might also like