SlideShare a Scribd company logo
Exception Handling in Java
What is an Exception in Java?
• An exception is an unwanted or unexpected event that occurs
during the execution of the program, that disrupts the flow of
the program.
• For example, if a user is trying to divide an integer by 0 then it
is an exception, as it is not possible mathematically.
• There are various types of interruptions while executing any
program like errors, exceptions, and bugs. These interruptions
can be due to programming mistakes or due to system issues.
Depending on the conditions they can be classified as errors
and exceptions.
• Java has classes that are used to handle built-in exceptions and
provision to create user-defined exceptions.
1. Exception
• Exceptions are unwanted conditions that disrupt the
flow of the program.
• Exceptions usually occur due to the code and can be
recovered.
• Exceptions can be of both checked(exceptions that are
checked by the compiler) and unchecked(exceptions
that cannot be checked by the compiler) type.
• They can occur at both run time and compile time.
• In Java, exceptions belong to java.lang.Exception class.
2. Error
• An error is also an unwanted condition but it is
caused due to lack of resources and indicates a
serious problem.
• Errors are irrecoverable, they cannot be handled
by the programmers.
• Errors are of unchecked type only.
• They can occur only at run time.
• In java, errors belong to java.lang.error class.
• Eg: OutOfMemmoryError.
What is Exception Handling in java?
• Exception handling in java is a mechanism to handle
unwanted interruptions like exceptions and
continue with the normal flow of the program.
• Java uses try-catch blocks and other keywords like
finally, throw, and throws to handle exceptions.
• JVM(Java Virtual Machine) by default handles
exceptions, when an exception is raised it will halt
the execution of the program and throw the
occurred exception.
Why Handle Java Exception?
• We handle exceptions in java to make sure the program
executes properly without any halt, which occurs when an
exception is raised.
• These exceptions are runtime as well as compile-time.
• They may be minor exceptions but can cause a problem in
executions of the program, hence it becomes necessary to
handle java exceptions. If java exceptions are not handled,
programs may crash and execution is halted in between.
• For example, if there is a program with some lines of code and
an exception occurs a mid-way after executing certain lines of
code, in this case, the execution terminates abruptly.
• But if the programmer handles the exceptions explicitly, all the
statements of code are executed properly and the flow of the
program is maintained.
Example program
• class SampleCode
• {
• public static void main(String args[])
• {
• Sysytem.out.println("Hello World!");
• int a = 10;
• int b = 0;
• System.out.println(a / b);
• System.out.println("Welcome to java programming.");
• System.out.println("Bye.")
• }
• }
Output
• Hello World!
• Exception in thread "main" java.lang.ArithmeticException: / by zero
• at SampleException.main(SampleException.java:8)
• In the above code, the first three lines in the main method
are executed properly.
• At the 4th line, an integer is divided by 0, which is not
possible and an exception is raised by JVM(Java Virtual
Machine).
• In this case, the exception is not handled by the
programmer which will halt the program in between by
throwing the exception, and the rest of the lines of code
won't be executed.
How does JVM handles an Exception?
• Java exceptions raised during the program execution are nothing but objects of
the respective exception class in the hierarchy shown above.
• The exceptions have a naming and inheritance hierarchy to the main exception
class in java i.e. Throwable class.
• All java exception objects support the toString() method, which returns the full
name of the exception class as an output to the command prompt, which helps
to understand the exceptional condition.
• Whenever an exception has occurred inside a method, the method creates an
exception object and hands it over to JVM.
• This object contains the name and description of the exception and the current
state of the program where the exception has occurred.
• This is called the process of object creation and handing it over to JVM is known
as throwing an Exception.
• This object is an exception that is further handled by JVM.
How does JVM handles an Exception?
• When an exception is raised there is an ordered list of
the methods that had been called by JVM to get the
method where the exception has occurred this list is
called Call Stack.
• JVM searches through this call stack to get the proper
code to handle the occurred exception, this code
block is known as an Exception handler.
• When an appropriate handler is found JVM handles
the exception according to the code in the handler
and shows the state of the program.
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Hierarchy of Java Exception Classes
• As java is an object-oriented language every
class extends the Object class. All exceptions
and errors are subclasses of class Throwable.
• Throwable is the base/superclass of exception
handling hierarchy in java. This class is further
extended in different classes like exception,
error, and so on.
Exception Hierarchy
• All exception and error types are subclasses of the
class Throwable, which is the base class of the hierarchy.
• One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.
• Another branch, Error is used by the Java run-time
system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is
an example of such an error.
Hierarchy of Java Exception Classes
Exception Hierarchy
Types of Exceptions
• Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
Types of Exceptions Handling in Java
• 1. Checked Exceptions
• Checked exceptions are those exceptions that are
checked at compile time by the compiler.
• The program will not compile if they are not handled.
• These exceptions are child classes of the Exception
class.
• IOException, ClassNotFoundException,
InvocationTargetException, and SQL Exception are a
few of the checked exceptions in Java.
Types of Exceptions Handling in Java
• 2. Unchecked Exceptions
• Unchecked exceptions are those exceptions that are
checked at run time by JVM, as the compiler cannot
check unchecked exceptions,
• The programs with unchecked exceptions get compiled
successfully but they give runtime errors if not handled.
• These are child classes of Runtime Exception Class.
• ArithmeticException, NullPointerException,
NumberFormatException, IndexOutOfBoundException
are a few of the unchecked exceptions in Java.
How does a Programmer Handles an
Exception?
• Customized exception handling in java is achieved using
five keywords: try, catch, throw, throws, and finally. Here
is how these keywords work in short.
• Try block contains the program statements that may
raise an exception.
• Catch block catches the raised exception and handles it.
• Throw keyword is used to explicitly throw an exception.
• Throws keyword is used to declare an exception.
• Finally block contains statements that must be executed
after the try block.
Example of Exception Handling in Java
• class ExceptionExample {
• public static void main(String args[]) {
• try {
• // Code that can raise exception
• int div = 509 / 0;
• } catch (ArithmeticException e) {
• System.out.println(e);
• }
• System.out.println("End of code");
• }
• }
• Output:
• java.lang.ArithmeticException: / by zero
• End of code
1. try block
• try block is used to execute doubtful statements which can throw exceptions.
• try block can have multiple statements.
• Try block cannot be executed on itself, there has to be at least one catch block
or finally block with a try block.
• When any exception occurs in a try block, the appropriate exception object
will be redirected to the catch block, this catch block will handle the
exception according to statements in it and continue the further execution.
• The control of execution goes from the try block to the catch block once an
exception occurs.
• Syntax
• try {
• //Doubtfull Statements.
• }
2. catch block
• catch block is used to give a solution or alternative for an exception.
• catch block is used to handle the exception by declaring the type of
exception within the parameter.
• The declared exception must be the parent class exception or the generated
exception type in the exception class hierarchy or a user-defined exception.
• You can use multiple catch blocks with a single try block.
• Syntax
• try {
• //Doubtful Statements
• }
• catch(Exception e)
• {
• }
1. try-catch block
• public class Main {
• public static void main(String[ ] args) {
• try {
• int[] myNumbers = {10, 1, 2, 3, 5, 11};
• System.out.println(myNumbers[10]);
• } catch (Exception e) {
• System.out.println("Something went wrong.");
• }
• }
• }
• Output:
• Something went wrong.
• In this program, the user has declared an array
myNumbers in the try block, which has some
numbers stored in it. And the user is trying to access
an element of the array that is stored at the 10th
position.
• But array has only 6 elements and the highest
address position is 5. By doing this user is trying to
access an element that is not present in the array,
this will raise an exception, and the catch block will
get executed.
2. Multiple Catch Blocks
• Java can have a single try block and multiple
catch blocks and a relevant catch block gets
executed.
• Example 1:
• Here we are giving doubtful statements in a
try block and using multiple catch blocks to
handle the exception that will occur according
to the statement.
• public class MultipleCatchBlock1 {
• public static void main(String[] args) {
• try {
• int a[] = new int[5];
• a[5] = 30 / 0;
• } catch (ArithmeticException e) {
• System.out.println("Arithmetic Exception occurs");
• } catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("ArrayIndexOutOfBounds Exception occurs");
• } catch (Exception e) {
• System.out.println("Parent Exception occurs");
• }
• System.out.println("End of the code");
• }
• }
• Output:
• Arithmetic Exception occurs
• End of the code
• In this example, the try block has doubtful statements that
are trying to divide an integer by 0 and 3 catch blocks which
have mentioned the exceptions that can handle.
• After execution of the try block, the Arithmetic Exception is
raised and JVM starts to search for the catch block to handle
the same.
• JVM will find the first catch block that can handle the raised
exception, and control will be passed to that catch block.
• After the exception is handled the flow of the program
comes out from try-catch block and it will execute the rest
of the code.
• public class MultipleCatchBlock2 {
• public static void main(String[] args) {
• try {
• int a[] = new int[5];
• System.out.println(a[10]);
• } catch (ArithmeticException e) {
• System.out.println("Arithmetic Exception occurs");
• } catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("ArrayIndexOutOfBounds Exception occurs");
• } catch (Exception e) {
• System.out.println("Parent Exception occurs");
• }
• System.out.println("rest of the code");
• }
• }
• Output:
• ArrayIndexOutOfBounds Exception occurs
• rest of the code
• In this example, try block has doubtful statements that are trying
to access elements that are not present in an array and 3 catch
blocks that have mentioned the exceptions that can handle.
• After execution of try block, ArrayIndexOutOfBounds Exception is
raised and JVM starts to search for the catch block to handle the
same.
• JVM will find the second catch block that can handle the raised
exception, and control will be passed to that catch block.
• After the exception is handled the flow of the program comes
out from try-catch block and it will execute rest of the code.
3. Nested Try Catch
• class NestingDemo {
• public static void main(String args[]) {
• //main try-block
• try {
• //try-block2
• try {
• //try-block3
• try {
• int arr[] = {
• 1,
• 2,
• 3,
• 4
• };
• /* I'm trying to display the value of
• * an element which doesn't exist. The
• * code should throw an exception
• */
• System.out.println(arr[10]);
• } catch (ArithmeticException e) {
• System.out.print("Arithmetic Exception");
• System.out.println(" handled in try-block3");
• }
• } catch (ArithmeticException e) {
• System.out.print("Arithmetic Exception");
• System.out.println(" handled in try-block2");
• }
• } catch (ArithmeticException e3) {
• System.out.print("Arithmetic Exception");
• System.out.println(" handled in main try-block");
• } catch (ArrayIndexOutOfBoundsException e4) {
• System.out.print("ArrayIndexOutOfBoundsException");
• System.out.println(" handled in main try-block");
• } catch (Exception e5) {
• System.out.print("Exception");
• System.out.println(" handled in main try-block");
• }
• }
• }
• Output:
• ArrayIndexOutOfBoundsException handled in main try-block
3. Nested Try Catch
• As you can see that the ArrayIndexOutOfBoundsException
occurred in the grandchild try-block3.
• Since try-block3 is not handling this exception, the control
then gets transferred to the parent try-block2 and looked for
the catch handlers in try-block2.
• Since the try-block2 is also not handling that exception, the
control gets transferred to the main (grandparent) try-block
where it found the appropriate catch block for an exception.
• We can use the finally block after the main try-catch block if
required.
4. finally block
• finally block is associated with a try, catch block.
• It is executed every time irrespective of
exception is thrown or not.
• finally block is used to execute important
statements such as closing statement, release
the resources, and release memory also.
• finally block can be used with try block with or
without catch block.
Syntax
• try
• {
• //Doubtful Statements
• }
• catch(Exception e)
• {
•
• }
• finally
• {
• //Close resources
• }
Example:
• public class Main {
• public static void main(String[] args) {
• try {
• int data = 100/0;
• System.out.println(data);
• } catch (Exception e) {
• System.out.println("Can't divide integer by 0!");
• } finally {
• System.out.println("The 'try catch' is finished.");
• }
• }
• }
• Output:
• Can't divide integer by 0!
• The 'try catch' is finished.
• Here, after the execution of try and catch blocks, finally block gets executed. finally block gets
executed even if the catch block is not executed.
throw
• The throw keyword in Java is used to explicitly throw an exception
from a method or any block of code. We can throw either checked or
unchecked exception. The throw keyword is mainly used to throw
custom exceptions.
• Syntax in Java throw
• throw Instance
• Example:
• throw new ArithmeticException("/ by zero");
• But this exception i.e., Instance must be of type Throwable or a
subclass of Throwable.
Throw Keyword
• The flow of execution of the program stops
immediately after the throw statement is
executed and the nearest enclosing try block is
checked to see if it has a catch statement that
matches the type of exception.
• If it finds a match, controlled is transferred to
that statement otherwise next
enclosing try block is checked, and so on.
• If no matching catch is found then the default
exception handler will halt the program.
Throw Keyword
• // Java program that demonstrates the use of throw
• class ThrowExcep {
• static void fun()
• {
• try {
• throw new NullPointerException("demo");
• }
• catch (NullPointerException e) {
• System.out.println("Caught inside fun().");
• throw e; // rethrowing the exception
• }
• }
• public static void main(String args[])
• {
• try {
• fun();
• }
• catch (NullPointerException e) {
• System.out.println("Caught in main.");
• }
• }
• }
• Output
• Caught inside fun().
• Caught in main.
Throw Keyword
• // Java program that demonstrates
• // the use of throw
• class Test {
• public static void main(String[] args)
• {
• System.out.println(1 / 0);
• }
• }
• Output
• Exception in thread "main" java.lang.ArithmeticException: / by zero
Java throws
• throws is a keyword in Java that is used in the
signature of a method to indicate that this method
might throw one of the listed type exceptions. The
caller to these methods has to handle the exception
using a try-catch block.
• Syntax of Java throws
• type method_name(parameters) throws
exception_list exception_list is a comma separated
list of all the exceptions which a method might
throw.
Java throws
• In a program, if there is a chance of raising an exception then
the compiler always warns us about it and compulsorily we
should handle that checked exception, Otherwise, we will get
compile time error saying unreported exception XXX must be
caught or declared to be thrown. To prevent this compile time
error we can handle the exception in two ways:
• By using try catch
• By using the throws keyword
• We can use the throws keyword to delegate the responsibility
of exception handling to the caller (It may be a method or JVM)
then the caller method is responsible to handle that exception.
Java throws Examples
• // Java program to illustrate error in case
• // of unhandled exception
• class tst {
• public static void main(String[] args)
• {
• Thread.sleep(10000);
• System.out.println("Hello Students");
• }
• }
• Output
• error: unreported exception InterruptedException; must be caught or declared to be
thrown
• Explanation
• In the above program, we are getting compile time error because there is a chance of
exception if the main thread is going to sleep, other threads get the chance to
execute the main() method which will cause InterruptedException.
Java throws Examples
• // Java program to illustrate throws
• class tst {
• public static void main(String[] args)
• throws InterruptedException
• {
• Thread.sleep(10000);
• System.out.println("Hello Students");
• }
• }
• Output
• Hello Students
• Explanation
• In the above program, by using the throws keyword we handled the InterruptedException and
we will get the output as Hello Geeks
Java throws Examples
• // Java program to demonstrate working of throws
• class ThrowsExecp {
• static void fun() throws IllegalAccessException
• {
• System.out.println("Inside fun(). ");
• throw new IllegalAccessException("demo");
• }
• public static void main(String args[])
• {
• try {
• fun();
• }
• catch (IllegalAccessException e) {
• System.out.println("caught in main.");
• }
• }
• }
• Output
• Inside fun(). caught in main.
Java throws Keyword
• throws keyword is required only for checked
exceptions and usage of the throws keyword for
unchecked exceptions is meaningless.
• throws keyword is required only to convince the
compiler and usage of the throws keyword does not
prevent abnormal termination of the program.
• With the help of the throws keyword, we can
provide information to the caller of the method
about the exception.
Java Custom Exception
• In Java, we can create our own exceptions that
are derived classes of the Exception class.
Creating our own Exception is known as
custom exception or user-defined exception.
• Basically, Java custom exceptions are used to
customize the exception according to user
need.
Java Custom Exception
• Consider the example 1 in which
InvalidAgeException class extends the
Exception class.
• Using the custom exception, we can have your
own exception and message. Here, we have
passed a string to the constructor of superclass
i.e. Exception class that can be obtained using
getMessage() method on the object we have
created.
Java Custom Exception
• Following are few of the reasons to use custom
exceptions:
• To catch and provide specific treatment to a subset of
existing Java exceptions.
• Business logic exceptions: These are the exceptions
related to business logic and workflow. It is useful for
the application users or the developers to understand
the exact problem.
• In order to create custom exception, we need to extend
Exception class that belongs to java.lang package.
Example
• Consider the following example, where we create a
custom exception named WrongFileNameException:
• public class WrongFileNameException extends Exception
• {
• public WrongFileNameException(String errorMessage)
• {
• super(errorMessage);
• }
• }

More Related Content

PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
PPTX
Java Exceptions and Exception Handling
PPTX
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
PPT
A36519192_21789_4_2018_Exception Handling.ppt
PPTX
Introduction to java exceptions
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Chap2 exception handling
PPTX
Lec-01 Exception Handling in Java_javatpoint.pptx
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Java Exceptions and Exception Handling
Week 4 - 5 Debugging Code and Analyzing Logic Errors.pptx
A36519192_21789_4_2018_Exception Handling.ppt
Introduction to java exceptions
Java-Unit 3- Chap2 exception handling
Chap2 exception handling
Lec-01 Exception Handling in Java_javatpoint.pptx

Similar to using Java Exception Handling in Java.pptx (20)

PDF
Ch-1_5.pdf this is java tutorials for all
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPTX
Exceptionhandling
PPTX
Exception Handling.pptx
PPTX
Exceptions in Java
PPTX
Exception handling in java
PPTX
Exception handling in java-PPT.pptx
PPTX
Exception handling
PPTX
UNIT-3.pptx Exception Handling and Multithreading
PPTX
Javasession4
PPTX
Exception handling in java.pptx
PPT
exception-handling-in-java.ppt unit 2
PPTX
Exception handling in java
PDF
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
PDF
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
PDF
Chapter 5 Exception Handling (1).pdf
PPTX
EXCEPTION HANDLING in prograaming
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPT
Exception handling
Ch-1_5.pdf this is java tutorials for all
UNIT III 2021R.pptx
UNIT III 2021R.pptx
Exceptionhandling
Exception Handling.pptx
Exceptions in Java
Exception handling in java
Exception handling in java-PPT.pptx
Exception handling
UNIT-3.pptx Exception Handling and Multithreading
Javasession4
Exception handling in java.pptx
exception-handling-in-java.ppt unit 2
Exception handling in java
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
JAVA UNIT-2 ONE SHOT NOTES_64156529_2025_07_12_10__250712_103642.pdf
Chapter 5 Exception Handling (1).pdf
EXCEPTION HANDLING in prograaming
unit 4 msbte syallbus for sem 4 2024-2025
Exception handling
Ad

More from AshokRachapalli1 (20)

PPTX
structure of dbms1 power point presentation
PPTX
DBMS Introduction-Unit 1 power point presentation
PPT
215-Database-Recovery presentation document
PPTX
transactionprocessing-220423112118 (1).pptx
PPTX
unit-1 lecture 7 Types of system calls.pptx
PPTX
DATA MODEL Power point presentation for dbms
PPTX
WEEK-2 DML and operators power point presentation
PPTX
Relational Algebra in DBMS 2025 power point
PPTX
CLOSURE OF AN ATTRIBUTE powerpontpresentatio
PPT
Relational algebra in database management system
PPT
DBMS-3.1 Normalization upto boyscodd normal form
PPTX
Data base Users and Administrator pptx
PPTX
Database Languages power point presentation
PPTX
Relational Algebra in DBMS power ppoint pesenetation
PPTX
Multi-Threading in Java power point presenetation
PPT
ARRAYS in java with in details presentation.ppt
PPT
lecture-a-java-review .. this review ppt will help to the lectureres
PPTX
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
PPTX
joins in dbms its describes about how joins are important and necessity in d...
PPTX
6.Database Languages lab-1.pptx
structure of dbms1 power point presentation
DBMS Introduction-Unit 1 power point presentation
215-Database-Recovery presentation document
transactionprocessing-220423112118 (1).pptx
unit-1 lecture 7 Types of system calls.pptx
DATA MODEL Power point presentation for dbms
WEEK-2 DML and operators power point presentation
Relational Algebra in DBMS 2025 power point
CLOSURE OF AN ATTRIBUTE powerpontpresentatio
Relational algebra in database management system
DBMS-3.1 Normalization upto boyscodd normal form
Data base Users and Administrator pptx
Database Languages power point presentation
Relational Algebra in DBMS power ppoint pesenetation
Multi-Threading in Java power point presenetation
ARRAYS in java with in details presentation.ppt
lecture-a-java-review .. this review ppt will help to the lectureres
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
joins in dbms its describes about how joins are important and necessity in d...
6.Database Languages lab-1.pptx
Ad

Recently uploaded (20)

PDF
Complications of Minimal Access Surgery at WLH
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
RMMM.pdf make it easy to upload and study
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Classroom Observation Tools for Teachers
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Basic Mud Logging Guide for educational purpose
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Institutional Correction lecture only . . .
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Lesson notes of climatology university.
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
Complications of Minimal Access Surgery at WLH
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Anesthesia in Laparoscopic Surgery in India
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
RMMM.pdf make it easy to upload and study
Microbial disease of the cardiovascular and lymphatic systems
Classroom Observation Tools for Teachers
Renaissance Architecture: A Journey from Faith to Humanism
Basic Mud Logging Guide for educational purpose
Computing-Curriculum for Schools in Ghana
Institutional Correction lecture only . . .
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Supply Chain Operations Speaking Notes -ICLT Program
Insiders guide to clinical Medicine.pdf
Lesson notes of climatology university.
Abdominal Access Techniques with Prof. Dr. R K Mishra
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Module 4: Burden of Disease Tutorial Slides S2 2025

using Java Exception Handling in Java.pptx

  • 2. What is an Exception in Java? • An exception is an unwanted or unexpected event that occurs during the execution of the program, that disrupts the flow of the program. • For example, if a user is trying to divide an integer by 0 then it is an exception, as it is not possible mathematically. • There are various types of interruptions while executing any program like errors, exceptions, and bugs. These interruptions can be due to programming mistakes or due to system issues. Depending on the conditions they can be classified as errors and exceptions. • Java has classes that are used to handle built-in exceptions and provision to create user-defined exceptions.
  • 3. 1. Exception • Exceptions are unwanted conditions that disrupt the flow of the program. • Exceptions usually occur due to the code and can be recovered. • Exceptions can be of both checked(exceptions that are checked by the compiler) and unchecked(exceptions that cannot be checked by the compiler) type. • They can occur at both run time and compile time. • In Java, exceptions belong to java.lang.Exception class.
  • 4. 2. Error • An error is also an unwanted condition but it is caused due to lack of resources and indicates a serious problem. • Errors are irrecoverable, they cannot be handled by the programmers. • Errors are of unchecked type only. • They can occur only at run time. • In java, errors belong to java.lang.error class. • Eg: OutOfMemmoryError.
  • 5. What is Exception Handling in java? • Exception handling in java is a mechanism to handle unwanted interruptions like exceptions and continue with the normal flow of the program. • Java uses try-catch blocks and other keywords like finally, throw, and throws to handle exceptions. • JVM(Java Virtual Machine) by default handles exceptions, when an exception is raised it will halt the execution of the program and throw the occurred exception.
  • 6. Why Handle Java Exception? • We handle exceptions in java to make sure the program executes properly without any halt, which occurs when an exception is raised. • These exceptions are runtime as well as compile-time. • They may be minor exceptions but can cause a problem in executions of the program, hence it becomes necessary to handle java exceptions. If java exceptions are not handled, programs may crash and execution is halted in between. • For example, if there is a program with some lines of code and an exception occurs a mid-way after executing certain lines of code, in this case, the execution terminates abruptly. • But if the programmer handles the exceptions explicitly, all the statements of code are executed properly and the flow of the program is maintained.
  • 7. Example program • class SampleCode • { • public static void main(String args[]) • { • Sysytem.out.println("Hello World!"); • int a = 10; • int b = 0; • System.out.println(a / b); • System.out.println("Welcome to java programming."); • System.out.println("Bye.") • } • }
  • 8. Output • Hello World! • Exception in thread "main" java.lang.ArithmeticException: / by zero • at SampleException.main(SampleException.java:8) • In the above code, the first three lines in the main method are executed properly. • At the 4th line, an integer is divided by 0, which is not possible and an exception is raised by JVM(Java Virtual Machine). • In this case, the exception is not handled by the programmer which will halt the program in between by throwing the exception, and the rest of the lines of code won't be executed.
  • 9. How does JVM handles an Exception? • Java exceptions raised during the program execution are nothing but objects of the respective exception class in the hierarchy shown above. • The exceptions have a naming and inheritance hierarchy to the main exception class in java i.e. Throwable class. • All java exception objects support the toString() method, which returns the full name of the exception class as an output to the command prompt, which helps to understand the exceptional condition. • Whenever an exception has occurred inside a method, the method creates an exception object and hands it over to JVM. • This object contains the name and description of the exception and the current state of the program where the exception has occurred. • This is called the process of object creation and handing it over to JVM is known as throwing an Exception. • This object is an exception that is further handled by JVM.
  • 10. How does JVM handles an Exception? • When an exception is raised there is an ordered list of the methods that had been called by JVM to get the method where the exception has occurred this list is called Call Stack. • JVM searches through this call stack to get the proper code to handle the occurred exception, this code block is known as an Exception handler. • When an appropriate handler is found JVM handles the exception according to the code in the handler and shows the state of the program.
  • 11. Major reasons why an exception Occurs • Invalid user input • Device failure • Loss of network connection • Physical limitations (out-of-disk memory) • Code errors • Out of bound • Null reference • Type mismatch • Opening an unavailable file • Database errors • Arithmetic errors
  • 12. Hierarchy of Java Exception Classes • As java is an object-oriented language every class extends the Object class. All exceptions and errors are subclasses of class Throwable. • Throwable is the base/superclass of exception handling hierarchy in java. This class is further extended in different classes like exception, error, and so on.
  • 13. Exception Hierarchy • All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. • One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. • Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
  • 14. Hierarchy of Java Exception Classes
  • 16. Types of Exceptions • Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.
  • 17. Types of Exceptions Handling in Java • 1. Checked Exceptions • Checked exceptions are those exceptions that are checked at compile time by the compiler. • The program will not compile if they are not handled. • These exceptions are child classes of the Exception class. • IOException, ClassNotFoundException, InvocationTargetException, and SQL Exception are a few of the checked exceptions in Java.
  • 18. Types of Exceptions Handling in Java • 2. Unchecked Exceptions • Unchecked exceptions are those exceptions that are checked at run time by JVM, as the compiler cannot check unchecked exceptions, • The programs with unchecked exceptions get compiled successfully but they give runtime errors if not handled. • These are child classes of Runtime Exception Class. • ArithmeticException, NullPointerException, NumberFormatException, IndexOutOfBoundException are a few of the unchecked exceptions in Java.
  • 19. How does a Programmer Handles an Exception? • Customized exception handling in java is achieved using five keywords: try, catch, throw, throws, and finally. Here is how these keywords work in short. • Try block contains the program statements that may raise an exception. • Catch block catches the raised exception and handles it. • Throw keyword is used to explicitly throw an exception. • Throws keyword is used to declare an exception. • Finally block contains statements that must be executed after the try block.
  • 20. Example of Exception Handling in Java • class ExceptionExample { • public static void main(String args[]) { • try { • // Code that can raise exception • int div = 509 / 0; • } catch (ArithmeticException e) { • System.out.println(e); • } • System.out.println("End of code"); • } • } • Output: • java.lang.ArithmeticException: / by zero • End of code
  • 21. 1. try block • try block is used to execute doubtful statements which can throw exceptions. • try block can have multiple statements. • Try block cannot be executed on itself, there has to be at least one catch block or finally block with a try block. • When any exception occurs in a try block, the appropriate exception object will be redirected to the catch block, this catch block will handle the exception according to statements in it and continue the further execution. • The control of execution goes from the try block to the catch block once an exception occurs. • Syntax • try { • //Doubtfull Statements. • }
  • 22. 2. catch block • catch block is used to give a solution or alternative for an exception. • catch block is used to handle the exception by declaring the type of exception within the parameter. • The declared exception must be the parent class exception or the generated exception type in the exception class hierarchy or a user-defined exception. • You can use multiple catch blocks with a single try block. • Syntax • try { • //Doubtful Statements • } • catch(Exception e) • { • }
  • 23. 1. try-catch block • public class Main { • public static void main(String[ ] args) { • try { • int[] myNumbers = {10, 1, 2, 3, 5, 11}; • System.out.println(myNumbers[10]); • } catch (Exception e) { • System.out.println("Something went wrong."); • } • } • } • Output: • Something went wrong.
  • 24. • In this program, the user has declared an array myNumbers in the try block, which has some numbers stored in it. And the user is trying to access an element of the array that is stored at the 10th position. • But array has only 6 elements and the highest address position is 5. By doing this user is trying to access an element that is not present in the array, this will raise an exception, and the catch block will get executed.
  • 25. 2. Multiple Catch Blocks • Java can have a single try block and multiple catch blocks and a relevant catch block gets executed. • Example 1: • Here we are giving doubtful statements in a try block and using multiple catch blocks to handle the exception that will occur according to the statement.
  • 26. • public class MultipleCatchBlock1 { • public static void main(String[] args) { • try { • int a[] = new int[5]; • a[5] = 30 / 0; • } catch (ArithmeticException e) { • System.out.println("Arithmetic Exception occurs"); • } catch (ArrayIndexOutOfBoundsException e) { • System.out.println("ArrayIndexOutOfBounds Exception occurs"); • } catch (Exception e) { • System.out.println("Parent Exception occurs"); • } • System.out.println("End of the code"); • } • } • Output: • Arithmetic Exception occurs • End of the code
  • 27. • In this example, the try block has doubtful statements that are trying to divide an integer by 0 and 3 catch blocks which have mentioned the exceptions that can handle. • After execution of the try block, the Arithmetic Exception is raised and JVM starts to search for the catch block to handle the same. • JVM will find the first catch block that can handle the raised exception, and control will be passed to that catch block. • After the exception is handled the flow of the program comes out from try-catch block and it will execute the rest of the code.
  • 28. • public class MultipleCatchBlock2 { • public static void main(String[] args) { • try { • int a[] = new int[5]; • System.out.println(a[10]); • } catch (ArithmeticException e) { • System.out.println("Arithmetic Exception occurs"); • } catch (ArrayIndexOutOfBoundsException e) { • System.out.println("ArrayIndexOutOfBounds Exception occurs"); • } catch (Exception e) { • System.out.println("Parent Exception occurs"); • } • System.out.println("rest of the code"); • } • } • Output: • ArrayIndexOutOfBounds Exception occurs • rest of the code
  • 29. • In this example, try block has doubtful statements that are trying to access elements that are not present in an array and 3 catch blocks that have mentioned the exceptions that can handle. • After execution of try block, ArrayIndexOutOfBounds Exception is raised and JVM starts to search for the catch block to handle the same. • JVM will find the second catch block that can handle the raised exception, and control will be passed to that catch block. • After the exception is handled the flow of the program comes out from try-catch block and it will execute rest of the code.
  • 30. 3. Nested Try Catch • class NestingDemo { • public static void main(String args[]) { • //main try-block • try { • //try-block2 • try { • //try-block3 • try { • int arr[] = { • 1, • 2, • 3, • 4 • }; • /* I'm trying to display the value of • * an element which doesn't exist. The • * code should throw an exception • */ • System.out.println(arr[10]); • } catch (ArithmeticException e) { • System.out.print("Arithmetic Exception"); • System.out.println(" handled in try-block3"); • } • } catch (ArithmeticException e) { • System.out.print("Arithmetic Exception"); • System.out.println(" handled in try-block2"); • } • } catch (ArithmeticException e3) { • System.out.print("Arithmetic Exception"); • System.out.println(" handled in main try-block"); • } catch (ArrayIndexOutOfBoundsException e4) { • System.out.print("ArrayIndexOutOfBoundsException"); • System.out.println(" handled in main try-block"); • } catch (Exception e5) { • System.out.print("Exception"); • System.out.println(" handled in main try-block"); • } • } • } • Output: • ArrayIndexOutOfBoundsException handled in main try-block
  • 31. 3. Nested Try Catch • As you can see that the ArrayIndexOutOfBoundsException occurred in the grandchild try-block3. • Since try-block3 is not handling this exception, the control then gets transferred to the parent try-block2 and looked for the catch handlers in try-block2. • Since the try-block2 is also not handling that exception, the control gets transferred to the main (grandparent) try-block where it found the appropriate catch block for an exception. • We can use the finally block after the main try-catch block if required.
  • 32. 4. finally block • finally block is associated with a try, catch block. • It is executed every time irrespective of exception is thrown or not. • finally block is used to execute important statements such as closing statement, release the resources, and release memory also. • finally block can be used with try block with or without catch block.
  • 33. Syntax • try • { • //Doubtful Statements • } • catch(Exception e) • { • • } • finally • { • //Close resources • }
  • 34. Example: • public class Main { • public static void main(String[] args) { • try { • int data = 100/0; • System.out.println(data); • } catch (Exception e) { • System.out.println("Can't divide integer by 0!"); • } finally { • System.out.println("The 'try catch' is finished."); • } • } • } • Output: • Can't divide integer by 0! • The 'try catch' is finished. • Here, after the execution of try and catch blocks, finally block gets executed. finally block gets executed even if the catch block is not executed.
  • 35. throw • The throw keyword in Java is used to explicitly throw an exception from a method or any block of code. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exceptions. • Syntax in Java throw • throw Instance • Example: • throw new ArithmeticException("/ by zero"); • But this exception i.e., Instance must be of type Throwable or a subclass of Throwable.
  • 36. Throw Keyword • The flow of execution of the program stops immediately after the throw statement is executed and the nearest enclosing try block is checked to see if it has a catch statement that matches the type of exception. • If it finds a match, controlled is transferred to that statement otherwise next enclosing try block is checked, and so on. • If no matching catch is found then the default exception handler will halt the program.
  • 37. Throw Keyword • // Java program that demonstrates the use of throw • class ThrowExcep { • static void fun() • { • try { • throw new NullPointerException("demo"); • } • catch (NullPointerException e) { • System.out.println("Caught inside fun()."); • throw e; // rethrowing the exception • } • } • public static void main(String args[]) • { • try { • fun(); • } • catch (NullPointerException e) { • System.out.println("Caught in main."); • } • } • } • Output • Caught inside fun(). • Caught in main.
  • 38. Throw Keyword • // Java program that demonstrates • // the use of throw • class Test { • public static void main(String[] args) • { • System.out.println(1 / 0); • } • } • Output • Exception in thread "main" java.lang.ArithmeticException: / by zero
  • 39. Java throws • throws is a keyword in Java that is used in the signature of a method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block. • Syntax of Java throws • type method_name(parameters) throws exception_list exception_list is a comma separated list of all the exceptions which a method might throw.
  • 40. Java throws • In a program, if there is a chance of raising an exception then the compiler always warns us about it and compulsorily we should handle that checked exception, Otherwise, we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: • By using try catch • By using the throws keyword • We can use the throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then the caller method is responsible to handle that exception.
  • 41. Java throws Examples • // Java program to illustrate error in case • // of unhandled exception • class tst { • public static void main(String[] args) • { • Thread.sleep(10000); • System.out.println("Hello Students"); • } • } • Output • error: unreported exception InterruptedException; must be caught or declared to be thrown • Explanation • In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute the main() method which will cause InterruptedException.
  • 42. Java throws Examples • // Java program to illustrate throws • class tst { • public static void main(String[] args) • throws InterruptedException • { • Thread.sleep(10000); • System.out.println("Hello Students"); • } • } • Output • Hello Students • Explanation • In the above program, by using the throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
  • 43. Java throws Examples • // Java program to demonstrate working of throws • class ThrowsExecp { • static void fun() throws IllegalAccessException • { • System.out.println("Inside fun(). "); • throw new IllegalAccessException("demo"); • } • public static void main(String args[]) • { • try { • fun(); • } • catch (IllegalAccessException e) { • System.out.println("caught in main."); • } • } • } • Output • Inside fun(). caught in main.
  • 44. Java throws Keyword • throws keyword is required only for checked exceptions and usage of the throws keyword for unchecked exceptions is meaningless. • throws keyword is required only to convince the compiler and usage of the throws keyword does not prevent abnormal termination of the program. • With the help of the throws keyword, we can provide information to the caller of the method about the exception.
  • 45. Java Custom Exception • In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. • Basically, Java custom exceptions are used to customize the exception according to user need.
  • 46. Java Custom Exception • Consider the example 1 in which InvalidAgeException class extends the Exception class. • Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.
  • 47. Java Custom Exception • Following are few of the reasons to use custom exceptions: • To catch and provide specific treatment to a subset of existing Java exceptions. • Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem. • In order to create custom exception, we need to extend Exception class that belongs to java.lang package.
  • 48. Example • Consider the following example, where we create a custom exception named WrongFileNameException: • public class WrongFileNameException extends Exception • { • public WrongFileNameException(String errorMessage) • { • super(errorMessage); • } • }