0% found this document useful (0 votes)
39 views49 pages

R22 - JAVA UNIT - II (Exception Handling)

Exception handling

Uploaded by

alois.fahim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views49 pages

R22 - JAVA UNIT - II (Exception Handling)

Exception handling

Uploaded by

alois.fahim
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Lecture on

JAVA
Exception Handling
M. S . B. KASYAPA
Assistant Professor
Topics
UNIT - II
Syllabus
Exception Handling: Exception and Error, Exception Types,
Exception Handler, Exception Handling Clauses – try, catch,
finally, throws and the throw statement, Built-in-Exceptions
and Custom Exceptions.
Files and I/O Streams: he file class, Streams, The Byte
Streams, Filtered Byte Streams, The Random Access File
class.

M S B KASYAPA
Exception & Error
★ In programming, errors are serious issues that prevent a
program from completing its task.
★ These are happens outside the control of the program,
such as running out of memory or a system crash.
★ Errors are represented by the Error class and its
subclasses.
★ Exceptions are unexpected conditions that a program
can handle.
★ Exceptions are represented by the Exception class and
its subclasses.

M S B KASYAPA
Exception & Error
Error Examples
OutOfMemoryError: Thrown when the JVM runs out of memory.
StackOverflowError: Thrown when the call stack overflows due to
too many method invocations.
NoClassDefFoundError: Thrown when a required class cannot be
found.
Exception Examples
NullPointerException: Thrown when a null reference is accessed.
IllegalArgumentException: Thrown when an illegal argument is
passed to a method.
IOException: Thrown when an I/O operation fails.

M S B KASYAPA
Exception & Error
Error Exception
Definition A critical issue that a normal A condition that a program
application should not catch should catch
Cause Unrecoverable system issues Unexpected events within
beyond program control the program
When it At runtime when the system At runtime and compile
occurs encounters resource limitations time.
How to Not meant to be caught within Can be caught and handled
handle the program. using try-catch blocks.

M S B KASYAPA
Errors in JAVA
★ In java, both Errors and Exceptions are the subclasses of
java.lang.Throwable class.
★ Error refers to an illegal operation performed by the user
which results in the abnormal working of the program.
★ Programming errors often remain undetected until the
program is compiled or executed.
★ Some of the errors inhibit the program from getting compiled
or executed. Thus errors should be removed before compiling
and executing. It is of three types:
Compile-time - Syntax Errors
Run-time - Infinity Recursion
Logical - Wrong Formulas
M S B KASYAPA
Exceptions in JAVA
★ In java, both Errors and Exceptions are the subclasses of
java.lang.Throwable class.
★ Exceptions are two types:
Checked Exception : These are checked at compile time and
must be handled using try-catch or declared with throws.
Unchecked Exception : These occur at runtime and do not
require mandatory handling.
Example: NullPointerException, ArithmeticException.

M S B KASYAPA
Exception & Error
Hierarchy :

M S B KASYAPA
Exceptions Handling
➔ When an exception occurs, it disrupts the program execution
flow or it gets terminated, and the system generates an error.
➔ We use the exception handling mechanism to avoid abnormal
termination of program execution.
➔ Java programming language has a very powerful and efficient
exception handling mechanism with a large number of
built-in classes to handle most of the exceptions
automatically.
➔ Exceptions handling can be done in two ways
User Defined Exception Handling - manual Exceptions
handling mechnanisams created by programmer.
Built in Exception Handling - By using built in classes for
handling exceptions
M S B KASYAPA
Exceptions
Hierarchy :

M S B KASYAPA
Exception Handler
★ An exception handler is a mechanism that catches and
manages exceptions to prevent program crashes.
★ Java has two exception handling models.
Termination Model
We can say that in termination model the error is so
critical there is no way to get back to where the
exception occurred.
Resumptive Model
In resumptive model we hope to continue the execution
after the exception is handled.

M S B KASYAPA
Exception Handler
★ resumptive model uses Exception Handling Clauses

M S B KASYAPA
Exception Handling Clauses
try Block
Used to enclose the code that may throw an exception.
catch Block
Handles the exception thrown in the try block.
finally Block
Contains cleanup code that always executes, whether
an exception occurs or not.
throws Keyword
Declares exceptions that a method may throw, used in
method signatures.
throw Statement
Used to explicitly throw an exception.
M S B KASYAPA
Exception Handling Clauses
General Syntax
try{
...
code to be tested
...
}
catch(ExceptionType object){
...
code for handling the exception
...
}
Note: try must contain one catch block or can have more

M S B KASYAPA
Taking Input in JAVA
★ Before delving into the concept of exceptions, it's essential
to understand how to handle user input.
★ User input allows programs to interact dynamically with
users, making applications more versatile and responsive.
★ Java provides several methods to capture user input, with
the Scanner class from the java.util package being one of
the most commonly used due to its simplicity and
versatility.
★ To use the Scanner class, create an object of the class and
use any of the available methods found in the Scanner

M S B KASYAPA
Taking Input in JAVA
Methods of Scanner Class:
Method Use
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads a int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user

M S B KASYAPA
Taking Input in JAVA
Syntax:
Object Creation
Scanner object = new Scanner();
Reading input
variable=object.requiredMethod();

Note: If you enter wrong input (e.g. text in a numerical input),


you will get an exception/error message (like
"InputMismatchException").

M S B KASYAPA
Scanner Example

M S B KASYAPA
Scanner Exception Example
Need of Exceptions :

M S B KASYAPA
Scanner Exception Handling Example

M S B KASYAPA
Handling Exceptions
★ The try block contains the code that might throw an exception.
Example: if i want take a value from user to divide 10 and print
it code can be written like

M S B KASYAPA
Handling Exceptions
★ If an exception occurs inside the try block, the remaining code
in try is skipped, and execution moves to the catch block.
★ The catch block handles exceptions thrown by the try block.
★ Multiple catch blocks can be used for different exception types.
Example: As the above example having division operation it
may possible to rise arithmetic exception division by zero. for
that we can write catch block as

M S B KASYAPA
Handling Exceptions
★ If an exception occurs inside the try block, the remaining code
in try is skipped, and execution moves to the catch block.
★ The catch block handles exceptions thrown by the try block.
★ Multiple catch blocks can be used for different exception types.
Example: As the above example having division operation it
may possible to rise arithmetic exception division by zero. for
that we can write catch block as

M S B KASYAPA
Handling Exceptions
if it executes perfectly the output will be like this :

M S B KASYAPA
Handling Exceptions
if arithmetic exceptions happen output will be like this :

M S B KASYAPA
Handling Exceptions
★ Other than than try and catch we can finally block for
additional information in exception handling.
★ The finally block contains code that will execute no matter
what, whether an exception occurs or not.
★ It is mainly used for clean-up operations, like closing a file or
database connection.
Example: for the above program if you want to show additional
information then we can write finally block as

M S B KASYAPA
Handling Exceptions
Program after finally block :

M S B KASYAPA
Handling Exceptions
What happens if no suitable catch block not available :
★ First it will do the Method Call Stack Traversal still if it is not
found Program will Terminate.
Exception Propagation (Method Call Stack Traversal)
★ Initially Java starts searching for a matching catch block in
the current method where the exception occurred.
★ If no matching catch block is found, the exception moves up
to the calling method.
★ This process continues up the call stack until a method has a
matching catch block.

M S B KASYAPA
Handling Exceptions
What happens if no suitable catch block not available :
Unhandled Exception Causes Program Termination
★ If no method in the entire call stack has a matching catch
block, the JVM terminates the program abnormally.
★ The JVM prints an error message (stack trace) indicating the
type of exception, its message, and where it occurred in the
code.
Example: for the above program we have written catch block for
handling arithmetic exceptions only. if any other exception
happens (like entering string instead of integer) the program
will automatically terminates.
M S B KASYAPA
Handling Exceptions
if suitable catch block not available the output will be:

M S B KASYAPA
Handling Exceptions
What happens if no suitable catch block not available :
★ After entering string instead of integer the program will
automatically terminates.
★ if you see the out it is showing program finished with exit
code 1.
★ in general exit code 0 means an exit without errors or issues.
exit code 1 means there was some issue / problem which
caused the program to exit.
★ It will not even execute finally block.

M S B KASYAPA
Handling Exceptions
Handling suitable catch block not available error:
★ To prevent an unhandled exception from crashing the
program, use a general Exception catch block.
★ A common exception catch block usually refers to catching
the parent Exception class.
★ This ensures that any unexpected exceptions are caught and
handled gracefully.
★ It should be placed after specific exception handlers like
ArithmeticException, NullPointerException, etc.

M S B KASYAPA
Handling Exceptions
Handling no suitable catch block not available :

M S B KASYAPA
Handling Exceptions
Handling no suitable catch block not available :
if input is 0 or string handle
if input is non 0 integer
exception

M S B KASYAPA
throw & throws
★ try-catch block used to handle the exception automatically.
★ It will allow you to rise a exception according to the user
requirement.
★ to solve this throw and throws will be used.
★ It will not even execute finally block.
Throw
★ The throw keyword is used to throw an exception instance
explicitly from a try block to corresponding catch block.
★ That means it is used to transfer the control from try block to
corresponding catch block.

M S B KASYAPA
throw & throws
Throw
★ The throw keyword must be used inside the try block.
★ When JVM encounters the throw keyword, it stops the
execution of try block and jump to the corresponding catch
block.
★ Using throw keyword only object of Throwable class or its
subclasses can be thrown.

M S B KASYAPA
throw & throws
Throw
★ The throw keyword must be used inside the try block.
★ When JVM encounters the throw keyword, it stops the
execution of try block and jump to the corresponding catch
block.
★ Using throw keyword only object of Throwable class or its
subclasses can be thrown.
★ It's followed by an instance of an exception object (e.g., throw
new IllegalArgumentException("Invalid argument");).

M S B KASYAPA
throw & throws
Throw Example: For try catch block example if we change the
code like this we can manually throw exceptions

M S B KASYAPA
throw & throws
Throw Example output :

M S B KASYAPA
throw & throws
Throws
★ The throws keyword specifies the exceptions that a method
can throw to the default handler and does not handle itself.
★ That means when we need a method to throw an exception
automatically, we use throws keyword followed by method
declaration.
★ It is mainly used for checked exceptions. Unchecked
exceptions do not require the throws keyword.
🔔 When a method throws an exception, we must put the calling
statement of method in try-catch block.

M S B KASYAPA
throw & throws
Throws Example

M S B KASYAPA
Exceptions Types
Exception handling can be down with to methods with use
built in exceptions and user defined exceptions

M S B KASYAPA
Exception Types
Checked Unchecked
Checked exceptions are found at Unchecked exceptions are found at
compile time. run time.
Derived from Exception class Derived from RuntimeException class
External factors like file I/O and Programming bugs like logical Error
database connection cause the cause the unchecked Exception.
checked Exception.
Must be handled using try-catch or Handling is optional, but good
declared with throws. practice for robust code.
Example:FileNotFoundException, Example:NullPointerException,
SQLException, IOException. ArrayIndexOutOfBoundsException.

M S B KASYAPA
Checked Exceptions
IOException: This is the most general exception related to input/output
operations. Ex: problems reading or writing files
FileNotFoundException: It is a subclass of IOException. (No File)
ClassNotFoundException: JVM tries to load a class but cannot find its
definition. happens when classpath mismatch, typo in the class name, A
required library is missing.
SQLException: error in a database operation. happens when Invalid
SQL syntax, Connection problems,Database access violations.
InstantiationException: create a new instance of a class fails (Abstract
class object creation)
UnknownHostException: It is a networking Exception. if it tries to
connect to the unknown IP address.

M S B KASYAPA
Unchecked Exceptions
ArithmeticException: when an exceptional arithmetic condition occurs.
Example: The most common cause is division by zero
NullPointerException: most frequent exceptions in Java. It occurs when
you try to access or modify an object that is null.
Example: String str = null; int length = str.length();
NumberFormatException: thrown when you try to convert a string to a
numeric type. Example: int num = Integer.parseInt("abc");
ArrayIndexOutOfBoundsException: try to access an element of an
array using an index that is outside the valid range of indices.
Example: int[] arr = {1, 2, 3}; int value = arr[3];
StringIndexOutOfBoundsException:similar to Array Index Exception,
but it applies to strings.
Example: String text = "hello"; char c = text.charAt(5);
M S B KASYAPA
Unchecked Exceptions

M S B KASYAPA
User Defined Exceptions
❖ The Java programming language allow us to create our own exception
classes which are basically subclasses built-in class Exception.
❖ To create our own exception class simply create a class as a subclass
of built-in Exception class.
❖ Basically custom exceptions are used to customize the exception
according to user needs.
❖ We may create constructor in the user-defined exception class and
pass a string to Exception class constructor using super().
❖ We can use getMessage() method to access the string.

M S B KASYAPA
User Defined Exceptions

M S B KASYAPA
Next Lecture on
JAVA
Files and I/O Streams
M. S . B. KASYAPA
Assistant Professor

You might also like