SlideShare a Scribd company logo
1
Exceptions
2
Introduction
 Rarely does a program runs successfully at
its very first attempt.
 It is common to make mistakes while
developing as well as typing a program.
 Such mistakes are categorised as:
 syntax errors - compilation errors.
 semantic errors– leads to programs producing
unexpected outputs.
 runtime errors – most often lead to abnormal
termination of programs or even cause the
system to crash.
3
Common Runtime Errors
 Dividing a number by zero.
 Accessing an element that is out of bounds of an
array.
 Trying to store incompatible data elements.
 Using negative value as array size.
 Trying to convert from string data to a specific data
value (e.g., converting string “abc” to integer value).
 File errors:

opening a file in “read mode” that does not exist or no read
permission

Opening a file in “write/update mode” which has “read
only” permission.
4
Without Error Handling – Example 1
class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
}
Program does not reach here
No compilation errors. While running it reports an error and stops without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
5
Traditional way of Error Handling -
Example 2
class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println(“Result is “ + a/b);
}
else{
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
Program reaches here
6
Error Handling
 Any program can find itself in unusual
circumstances – Error Conditions.
 A “good” program should be able to
handle these conditions gracefully.
 Java provides a mechanism to handle
these error condition - exceptions
7
Exceptions
 An exception is a condition that is caused
by a runtime error in the program.
 Provide a mechanism to signal errors
directly without using flags.
 Allow errors to be handled in one central
part of the code without cluttering code.
8
Exceptions and their Handling
 When the JVM encounters an error such as
divide by zero, it creates an exception object
and throws it – as a notification that an error
has occurred.
 If the exception object is not caught and
handled properly, the interpreter will display an
error and terminate the program.
 If we want the program to continue with
execution of the remaining code, then we
should try to catch the exception object thrown
by the error condition and then take
appropriate corrective actions. This task is
known as exception handling.
9
Common Java Exceptions
 ArithmeticException
 ArrayIndexOutOfBoundException
 ArrayStoreException
 FileNotFoundException
 IOException – general I/O failure
 NullPointerException – referencing a null object
 OutOfMemoryException
 SecurityException – when applet tries to perform an
action not allowed by the browser’s security setting.
 StackOverflowException
10
Exceptions in Java
 A method can signal an error condition
by throwing an exception – throws
 The calling method can transfer control
to a exception handler by catching an
exception - try, catch
 Clean up can be done by - finally
11
Exception Handling Mechanism
try Block
Statements that causes
an exception
catch Block
Statements that
handle the exception
Throws
exception
Object
12
Syntax of Exception Handling Code
…
…
try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
13
With Exception Handling - Example
3
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Program Reaches here
14
Multiple Catch Statements
 If a try block is likely to raise more than one type of exceptions, then
multiple catch blocks can be defined as follows:
…
…
try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
..
..
catch( Exception-TypeN e)
{
// statements to process exception N
}
…
15
finally block
 Java supports definition of another block called finally that be used to
handle any exception that is not caught by any of the previous statements.
It may be added immediately after the try block or after the last catch block:
…
try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
..
..
finally {
….
}
 When a finally is defined, it is executed regardless of whether or not an
exception is thrown. Therefore, it is also used to perform certain house
keeping operations such as closing files and releasing system resources.
16
Catching and Propagating
Exceptions
 Exceptions raised in try block can be
caught and then they can be thrown
again/propagated after performing
some operations. This can be done by
using the keyword “throw” as follows:
 throw exception-object;
17
With Exception Handling - Example
4
class WithExceptionCatchThrow{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
}
Program Does Not
reach here
when exception occurs
18
With Exception Handling - Example
5
class WithExceptionCatchThrowFinally{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
Program reaches
here
19
 Problem Statement :
 Consider the example of the Circle class
 Circle class had the following constructor
public Circle(double centreX, double centreY,
double radius){
x = centreX; y = centreY; r = radius;
}
 How would we ensure that the radius is not zero
or negative?
User-Defined Exceptions
20
Defining your own exceptions
import java.lang.Exception;
class InvalidRadiusException extends Exception {
private double r;
public InvalidRadiusException(double radius){
r = radius;
}
public void printError(){
System.out.println("Radius [" + r + "] is not valid");
}
}
21
Throwing the exception
class Circle {
double x, y, r;
public Circle (double centreX, double centreY,
double radius ) throws InvalidRadiusException {
if (r <= 0 ) {
throw new InvalidRadiusException(radius);
}
else {
x = centreX ; y = centreY; r = radius;
}
}
}
22
Catching the exception
class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(10, 10, -1);
System.out.println("Circle created");
}
catch(InvalidRadiusException e)
{
e.printError();
}
}
}
23
User-Defined Exceptions in
standard format
class MyException extends Exception
{
MyException(String message)
{
super(message); // pass to superclass if parameter is not handled by used defined exception
}
}
class TestMyException {
…
try {
..
throw new MyException(“This is error message”);
}
catch(MyException e)
{
System.out.println(“Message is: “+e.getMessage());
}
}
}
Get Message is a method defined in a standard
Exception class.
24
Summary
 A good programs does not produce
unexpected results.
 It is always a good practice to check for
potential problem spots in programs and
guard against program failures.
 Exceptions are mainly used to deal with
runtime errors.
 Exceptions also aid in debugging programs.
 Exception handling mechanisms can effectively
used to locate the type and place of errors.
25
Summary
 Try block, code that could have exceptions /
errors
 Catch block(s), specify code to handle various
types of exceptions. First block to have
appropriate type of exception is invoked.
 If no ‘local’ catch found, exception propagates
up the method call stack, all the way to main()
 Any execution of try, normal completion, or
catch then transfers control on to finally block

More Related Content

PPT
Exception handling in java
PPTX
Java -Exception handlingunit-iv
PPTX
JAVA Presenttation topics Programs.pptx
PDF
Class notes(week 8) on exception handling
PPTX
UNIT 2.pptx
PPT
Exception handling
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPTX
Interface andexceptions
Exception handling in java
Java -Exception handlingunit-iv
JAVA Presenttation topics Programs.pptx
Class notes(week 8) on exception handling
UNIT 2.pptx
Exception handling
unit 4 msbte syallbus for sem 4 2024-2025
Interface andexceptions

Similar to exception handling in java-123456789.ppt (20)

PPT
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
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
PPT
Md07 exceptions&assertion
PPTX
Exception handling
DOCX
Class notes(week 8) on exception handling
DOCX
Exception handling in java
PPTX
Exception handling in java
PPTX
Exceptions overview
PPTX
Java exception handling
PPT
Exception handling
PPT
Exception and ErrorHandling in Java .ppt
PPTX
java exception.pptx
DOCX
Java Exception handling
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Z blue exception
PPT
Java exception
PPT
Exceptions in java
Computer Object Oriented Programming - Chapter 4 - Excption Handling.ppt
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
Md07 exceptions&assertion
Exception handling
Class notes(week 8) on exception handling
Exception handling in java
Exception handling in java
Exceptions overview
Java exception handling
Exception handling
Exception and ErrorHandling in Java .ppt
java exception.pptx
Java Exception handling
Java-Exception Handling Presentation. 2024
Exception Handling In Java Presentation. 2024
Z blue exception
Java exception
Exceptions in java
Ad

More from Radhika Venkatesh (10)

PPTX
Inheritance in java-1234356789101112.pptx
PPTX
Module 3 and 4-javahjhhdhdhddhhdhdhdhd.pptx
PPTX
Module 4-Multithreading-1bzBXzxbbxxb.pptx
PPTX
Module-5-hjhjhjkhdjkhjhjhhhjhjhhhhj.pptx
PPTX
JAVA Module 2jdhgsjdsjdjsddsjjssdjdsjhsdjh.pptx
PPTX
Module--fundamentals and operators in java1.pptx
PPTX
Module 4-packages and exceptions in java.pptx
PPTX
JAVA Module 1______________________.pptx
PPTX
JAVA Module 2____________________--.pptx
PPT
memory systems-module 3 presentation ppt
Inheritance in java-1234356789101112.pptx
Module 3 and 4-javahjhhdhdhddhhdhdhdhd.pptx
Module 4-Multithreading-1bzBXzxbbxxb.pptx
Module-5-hjhjhjkhdjkhjhjhhhjhjhhhhj.pptx
JAVA Module 2jdhgsjdsjdjsddsjjssdjdsjhsdjh.pptx
Module--fundamentals and operators in java1.pptx
Module 4-packages and exceptions in java.pptx
JAVA Module 1______________________.pptx
JAVA Module 2____________________--.pptx
memory systems-module 3 presentation ppt
Ad

Recently uploaded (20)

PPTX
Artificial Intelligence
PPTX
communication and presentation skills 01
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PDF
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
PDF
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PPT
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
PPT
Total quality management ppt for engineering students
PPT
introduction to datamining and warehousing
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Fundamentals of Mechanical Engineering.pptx
PPT
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
PDF
737-MAX_SRG.pdf student reference guides
PPTX
UNIT - 3 Total quality Management .pptx
PDF
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PDF
PPT on Performance Review to get promotions
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PDF
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
PDF
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Artificial Intelligence
communication and presentation skills 01
86236642-Electric-Loco-Shed.pdf jfkduklg
Artificial Superintelligence (ASI) Alliance Vision Paper.pdf
Human-AI Collaboration: Balancing Agentic AI and Autonomy in Hybrid Systems
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
A5_DistSysCh1.ppt_INTRODUCTION TO DISTRIBUTED SYSTEMS
Total quality management ppt for engineering students
introduction to datamining and warehousing
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Fundamentals of Mechanical Engineering.pptx
INTRODUCTION -Data Warehousing and Mining-M.Tech- VTU.ppt
737-MAX_SRG.pdf student reference guides
UNIT - 3 Total quality Management .pptx
Unit I ESSENTIAL OF DIGITAL MARKETING.pdf
PPT on Performance Review to get promotions
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
SMART SIGNAL TIMING FOR URBAN INTERSECTIONS USING REAL-TIME VEHICLE DETECTI...
null (2) bgfbg bfgb bfgb fbfg bfbgf b.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...

exception handling in java-123456789.ppt

  • 2. 2 Introduction  Rarely does a program runs successfully at its very first attempt.  It is common to make mistakes while developing as well as typing a program.  Such mistakes are categorised as:  syntax errors - compilation errors.  semantic errors– leads to programs producing unexpected outputs.  runtime errors – most often lead to abnormal termination of programs or even cause the system to crash.
  • 3. 3 Common Runtime Errors  Dividing a number by zero.  Accessing an element that is out of bounds of an array.  Trying to store incompatible data elements.  Using negative value as array size.  Trying to convert from string data to a specific data value (e.g., converting string “abc” to integer value).  File errors:  opening a file in “read mode” that does not exist or no read permission  Opening a file in “write/update mode” which has “read only” permission.
  • 4. 4 Without Error Handling – Example 1 class NoErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; System.out.println(“Result is “ + a/b); System.out.println(“Program reached this line”); } } Program does not reach here No compilation errors. While running it reports an error and stops without executing further statements: java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
  • 5. 5 Traditional way of Error Handling - Example 2 class WithErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; if (b != 0){ System.out.println(“Result is “ + a/b); } else{ System.out.println(“ B is zero); } System.out.println(“Program is complete”); } } Program reaches here
  • 6. 6 Error Handling  Any program can find itself in unusual circumstances – Error Conditions.  A “good” program should be able to handle these conditions gracefully.  Java provides a mechanism to handle these error condition - exceptions
  • 7. 7 Exceptions  An exception is a condition that is caused by a runtime error in the program.  Provide a mechanism to signal errors directly without using flags.  Allow errors to be handled in one central part of the code without cluttering code.
  • 8. 8 Exceptions and their Handling  When the JVM encounters an error such as divide by zero, it creates an exception object and throws it – as a notification that an error has occurred.  If the exception object is not caught and handled properly, the interpreter will display an error and terminate the program.  If we want the program to continue with execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then take appropriate corrective actions. This task is known as exception handling.
  • 9. 9 Common Java Exceptions  ArithmeticException  ArrayIndexOutOfBoundException  ArrayStoreException  FileNotFoundException  IOException – general I/O failure  NullPointerException – referencing a null object  OutOfMemoryException  SecurityException – when applet tries to perform an action not allowed by the browser’s security setting.  StackOverflowException
  • 10. 10 Exceptions in Java  A method can signal an error condition by throwing an exception – throws  The calling method can transfer control to a exception handler by catching an exception - try, catch  Clean up can be done by - finally
  • 11. 11 Exception Handling Mechanism try Block Statements that causes an exception catch Block Statements that handle the exception Throws exception Object
  • 12. 12 Syntax of Exception Handling Code … … try { // statements } catch( Exception-Type e) { // statements to process exception } .. ..
  • 13. 13 With Exception Handling - Example 3 class WithExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); } System.out.println(“Program reached this line”); } } Program Reaches here
  • 14. 14 Multiple Catch Statements  If a try block is likely to raise more than one type of exceptions, then multiple catch blocks can be defined as follows: … … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 } .. .. catch( Exception-TypeN e) { // statements to process exception N } …
  • 15. 15 finally block  Java supports definition of another block called finally that be used to handle any exception that is not caught by any of the previous statements. It may be added immediately after the try block or after the last catch block: … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 } .. .. finally { …. }  When a finally is defined, it is executed regardless of whether or not an exception is thrown. Therefore, it is also used to perform certain house keeping operations such as closing files and releasing system resources.
  • 16. 16 Catching and Propagating Exceptions  Exceptions raised in try block can be caught and then they can be thrown again/propagated after performing some operations. This can be done by using the keyword “throw” as follows:  throw exception-object;
  • 17. 17 With Exception Handling - Example 4 class WithExceptionCatchThrow{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; } System.out.println(“Program is complete”); } } Program Does Not reach here when exception occurs
  • 18. 18 With Exception Handling - Example 5 class WithExceptionCatchThrowFinally{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(“Result is “ + r); } catch(ArithmeticException e){ System.out.println(“ B is zero); throw e; } finally{ System.out.println(“Program is complete”); } } } Program reaches here
  • 19. 19  Problem Statement :  Consider the example of the Circle class  Circle class had the following constructor public Circle(double centreX, double centreY, double radius){ x = centreX; y = centreY; r = radius; }  How would we ensure that the radius is not zero or negative? User-Defined Exceptions
  • 20. 20 Defining your own exceptions import java.lang.Exception; class InvalidRadiusException extends Exception { private double r; public InvalidRadiusException(double radius){ r = radius; } public void printError(){ System.out.println("Radius [" + r + "] is not valid"); } }
  • 21. 21 Throwing the exception class Circle { double x, y, r; public Circle (double centreX, double centreY, double radius ) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } else { x = centreX ; y = centreY; r = radius; } } }
  • 22. 22 Catching the exception class CircleTest { public static void main(String[] args){ try{ Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); } catch(InvalidRadiusException e) { e.printError(); } } }
  • 23. 23 User-Defined Exceptions in standard format class MyException extends Exception { MyException(String message) { super(message); // pass to superclass if parameter is not handled by used defined exception } } class TestMyException { … try { .. throw new MyException(“This is error message”); } catch(MyException e) { System.out.println(“Message is: “+e.getMessage()); } } } Get Message is a method defined in a standard Exception class.
  • 24. 24 Summary  A good programs does not produce unexpected results.  It is always a good practice to check for potential problem spots in programs and guard against program failures.  Exceptions are mainly used to deal with runtime errors.  Exceptions also aid in debugging programs.  Exception handling mechanisms can effectively used to locate the type and place of errors.
  • 25. 25 Summary  Try block, code that could have exceptions / errors  Catch block(s), specify code to handle various types of exceptions. First block to have appropriate type of exception is invoked.  If no ‘local’ catch found, exception propagates up the method call stack, all the way to main()  Any execution of try, normal completion, or catch then transfers control on to finally block