SlideShare a Scribd company logo
Exception Handling
Exception Handling
• An exception is an abnormal condition that
arises in a code sequence at run time.
• In other words, an exception is a run-time
error.
• Exceptions can be generated by the Java run-
time system, or they can be manually
generated by your code.
• Exceptions thrown by Java relate to fundamental
errors that violate the rules of the Java language
or the constraints of the Java execution
environment.
• Manually generated exceptions are typically used
to report some error condition to the caller of a
method.
• Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally
• The general form :
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed before try block ends
}
• All exception types are subclasses of the built-
in class Throwable.
• Exception, Error are the subclasses of
Throwable class.
Exception
• This is also the class that you will subclass to
create your own custom exception types.
• Eg:
division by zero
invalid array indexing.
Error
• which defines exceptions that are not
expected to be caught under normal
circumstances by your program.
• Eg:
Stack overflow
Using try and catch
• exception handler allows you to fix the error.
Second, it prevents the program from
automatically terminating.
• To guard against and handle a run-time error,
simply enclose the code that you want to
monitor inside a try block.
• If an exception occurs within the try block, it is
thrown.
• Your code can catch this exception (using
catch) and handle it in some rational manner.
Sample
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
• Output:
Division by zero.
After catch statement.
• Once an exception is thrown, program control
transfers out of the try block into the catch
block.
• Once the catch statement has executed,
program control continues with the next line
in the program following the entire try/catch
mechanism.
• The statements that are protected by try must
be surrounded by curly braces.
Displaying a Description of an
Exception
• Throwable overrides the toString( ) method
(defined by Object) so that it returns a string
containing a description of the exception.
Multiple catch Clauses
• In some cases, more than one exception could
be raised by a single piece of code.
• To handle this type of situation, you can
specify two or more catch clauses, each
catching a different type of exception.
• After one catch statement executes, the
others are bypassed, and execution continues
after the try/catch block
Sample
class MultiCatch {
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
System.out.println("After try/catch blocks.");
} }
• When you use multiple catch statements, it is
important to remember that exception
subclasses must come before any of their
superclasses.
• Checked exceptions :
– Checked Exceptions forces programmers to deal
with the exception that may be thrown.
– Checked exceptions must be caught at compile
time.
• Unchecked exceptions:
– Unchecked exceptions , however, the compiler
doesn’t force the programmers to either catch the
exception or declare it in a throws clause.
Nested try Statements
• The try statement can be nested.
• Sample
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present, the following statement will
generate a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used, then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
• Output:
C:>java NestTry
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:>java NestTry One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException
throw
• It is possible for your program to throw an
exception explicitly, using the throw
statement.
• The general form :
throw ThrowableInstance;
• ThrowableInstance must be an object of type
Throwable or a subclass of Throwable.
• The flow of execution stops immediately after
the throw statement; any subsequent
statements are not executed.
• The nearest enclosing try block is inspected to
see if it has a catch statement that matches
the type of the exception.
Sample
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
} }
throws
• If a method is capable of causing an exception
that it does not handle, it must specify this
behaviour so that callers of the method can
guard themselves against that exception.
• You do this by including a throws clause in the
method’s declaration.
• The general form:
– type method-name(parameter-list) throws
exception-list
– {
– // body of method
– }
class ThrowsDemo {
static void throwOne() throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught " + e);
}
} }
finally
• Any code that absolutely must be executed
before a method returns is put in a finally
block.
• The finally block will execute whether or not
an exception is thrown.
• This can be useful for closing file handles and
freeing up any other Resources.
• The finally clause is optional.
Sample
class FinallyDemo {
// Through an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
} finally {
System.out.println("procA's finally");
}
}
Java’s Built-in Exceptions
• unchecked exceptions - because the compiler
does not check to see if a method handles or
throws these exceptions.
• checked exceptions- Java defines several other
types of exceptions that relate to its various
class libraries
Unchecked Exception
Checked Exceptions
Creating Your Own Exception
Subclasses
• To create your own exception types to handle
situations specific to your applications, to do
so just define a subclass of Exception.
Sample
class MyException extends Exception {
private int detail;
MyException(int a) {
detail = a;
}
public String toString() {
return "MyException[" + detail + "]";
}
}
class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(20);
} catch (MyException e) {
System.out.println("Caught " + e);
}
} }
Chained Exceptions
• The chained exception feature allows you to
associate another exception with an
exception.

More Related Content

What's hot (13)

PPT
Exception handling
pooja kumari
 
PPTX
Pi j4.2 software-reliability
mcollison
 
PPTX
Exception handling in Java
Prasad Sawant
 
PPTX
130410107010 exception handling
Hemant Chetwani
 
PPSX
Exception Handling
Reddhi Basu
 
ODP
Exception handling in java
priyankazope
 
PPTX
Interface andexceptions
saman Iftikhar
 
PPTX
Exception handling in Java
Abhishek Pachisia
 
PPT
Exception handling in java
Pratik Soares
 
PPT
Exception handling
Tata Consultancy Services
 
PPTX
Exception handling chapter15
Kumar
 
PPTX
Java - Exception Handling
Prabhdeep Singh
 
PPT
Exception handling and templates
farhan amjad
 
Exception handling
pooja kumari
 
Pi j4.2 software-reliability
mcollison
 
Exception handling in Java
Prasad Sawant
 
130410107010 exception handling
Hemant Chetwani
 
Exception Handling
Reddhi Basu
 
Exception handling in java
priyankazope
 
Interface andexceptions
saman Iftikhar
 
Exception handling in Java
Abhishek Pachisia
 
Exception handling in java
Pratik Soares
 
Exception handling
Tata Consultancy Services
 
Exception handling chapter15
Kumar
 
Java - Exception Handling
Prabhdeep Singh
 
Exception handling and templates
farhan amjad
 

Similar to Java exception handling (20)

PPTX
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Tony Nguyen
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Fraboni Ec
 
PPT
Exception
Luis Goldster
 
PPT
Exception
Hoang Nguyen
 
PPT
Exception
Young Alista
 
PPT
Exception
James Wong
 
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
PPTX
L14 exception handling
teach4uin
 
PPT
8.Exception handling latest(MB).ppt .
happycocoman
 
PPT
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
PPTX
Java exception handling
Md. Tanvir Hossain
 
PPTX
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
PPTX
Java-Unit 3- Chap2 exception handling
raksharao
 
PPTX
Unit 4 exceptions and threads
DevaKumari Vijay
 
PPTX
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
PPTX
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
PPT
Exceptions in java
JasmeetSingh326
 
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Exception
Tony Nguyen
 
Exception
Tony Nguyen
 
Exception
Fraboni Ec
 
Exception
Fraboni Ec
 
Exception
Luis Goldster
 
Exception
Hoang Nguyen
 
Exception
Young Alista
 
Exception
James Wong
 
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
L14 exception handling
teach4uin
 
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java exception handling
Md. Tanvir Hossain
 
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java-Unit 3- Chap2 exception handling
raksharao
 
Unit 4 exceptions and threads
DevaKumari Vijay
 
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exceptions in java
JasmeetSingh326
 
Ad

More from GaneshKumarKanthiah (11)

PPTX
Software testing regression testing
GaneshKumarKanthiah
 
PPTX
Software testing acceptance testing
GaneshKumarKanthiah
 
PPTX
Software testing performance testing
GaneshKumarKanthiah
 
PPTX
Software testing introduction
GaneshKumarKanthiah
 
PPTX
Java string handling
GaneshKumarKanthiah
 
PPTX
Java packages
GaneshKumarKanthiah
 
PPT
Java introduction
GaneshKumarKanthiah
 
PPTX
Java interface
GaneshKumarKanthiah
 
PPT
Java inheritance
GaneshKumarKanthiah
 
PPT
Java awt
GaneshKumarKanthiah
 
PPTX
Java applet
GaneshKumarKanthiah
 
Software testing regression testing
GaneshKumarKanthiah
 
Software testing acceptance testing
GaneshKumarKanthiah
 
Software testing performance testing
GaneshKumarKanthiah
 
Software testing introduction
GaneshKumarKanthiah
 
Java string handling
GaneshKumarKanthiah
 
Java packages
GaneshKumarKanthiah
 
Java introduction
GaneshKumarKanthiah
 
Java interface
GaneshKumarKanthiah
 
Java inheritance
GaneshKumarKanthiah
 
Java applet
GaneshKumarKanthiah
 
Ad

Recently uploaded (20)

PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
July Patch Tuesday
Ivanti
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PPTX
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
PDF
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
PDF
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Python basic programing language for automation
DanialHabibi2
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Log-Based Anomaly Detection: Enhancing System Reliability with Machine Learning
Mohammed BEKKOUCHE
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
July Patch Tuesday
Ivanti
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
UiPath Academic Alliance Educator Panels: Session 2 - Business Analyst Content
DianaGray10
 
CIFDAQ Market Insights for July 7th 2025
CIFDAQ
 
Timothy Rottach - Ramp up on AI Use Cases, from Vector Search to AI Agents wi...
AWS Chicago
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
Fl Studio 24.2.2 Build 4597 Crack for Windows Free Download 2025
faizk77g
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Python basic programing language for automation
DanialHabibi2
 

Java exception handling

  • 2. Exception Handling • An exception is an abnormal condition that arises in a code sequence at run time. • In other words, an exception is a run-time error. • Exceptions can be generated by the Java run- time system, or they can be manually generated by your code.
  • 3. • Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. • Manually generated exceptions are typically used to report some error condition to the caller of a method. • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally
  • 4. • The general form : try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed before try block ends }
  • 5. • All exception types are subclasses of the built- in class Throwable. • Exception, Error are the subclasses of Throwable class.
  • 6. Exception • This is also the class that you will subclass to create your own custom exception types. • Eg: division by zero invalid array indexing.
  • 7. Error • which defines exceptions that are not expected to be caught under normal circumstances by your program. • Eg: Stack overflow
  • 8. Using try and catch • exception handler allows you to fix the error. Second, it prevents the program from automatically terminating. • To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block.
  • 9. • If an exception occurs within the try block, it is thrown. • Your code can catch this exception (using catch) and handle it in some rational manner.
  • 10. Sample class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } }
  • 11. • Output: Division by zero. After catch statement. • Once an exception is thrown, program control transfers out of the try block into the catch block. • Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
  • 12. • The statements that are protected by try must be surrounded by curly braces.
  • 13. Displaying a Description of an Exception • Throwable overrides the toString( ) method (defined by Object) so that it returns a string containing a description of the exception.
  • 14. Multiple catch Clauses • In some cases, more than one exception could be raised by a single piece of code. • To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. • After one catch statement executes, the others are bypassed, and execution continues after the try/catch block
  • 15. Sample class MultiCatch { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }
  • 16. • When you use multiple catch statements, it is important to remember that exception subclasses must come before any of their superclasses.
  • 17. • Checked exceptions : – Checked Exceptions forces programmers to deal with the exception that may be thrown. – Checked exceptions must be caught at compile time. • Unchecked exceptions: – Unchecked exceptions , however, the compiler doesn’t force the programmers to either catch the exception or declare it in a throws clause.
  • 18. Nested try Statements • The try statement can be nested. • Sample class NestTry { public static void main(String args[]) { try { int a = args.length; /* If no command-line args are present, the following statement will generate a divide-by-zero exception. */ int b = 42 / a; System.out.println("a = " + a); try { // nested try block /* If one command-line arg is used, then a divide-by-zero exception will be generated by the following code. */ if(a==1) a = a/(a-a); // division by zero
  • 19. /* If two command-line args are used, then generate an out-of-bounds exception. */ if(a==2) { int c[] = { 1 }; c[42] = 99; // generate an out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index out-of-bounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } } }
  • 20. • Output: C:>java NestTry Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One a = 1 Divide by 0: java.lang.ArithmeticException: / by zero C:>java NestTry One Two a = 2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException
  • 21. throw • It is possible for your program to throw an exception explicitly, using the throw statement. • The general form : throw ThrowableInstance; • ThrowableInstance must be an object of type Throwable or a subclass of Throwable.
  • 22. • The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. • The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception.
  • 23. Sample class ThrowDemo { static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); } } public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } }
  • 24. throws • If a method is capable of causing an exception that it does not handle, it must specify this behaviour so that callers of the method can guard themselves against that exception. • You do this by including a throws clause in the method’s declaration. • The general form: – type method-name(parameter-list) throws exception-list – { – // body of method – }
  • 25. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } }
  • 26. finally • Any code that absolutely must be executed before a method returns is put in a finally block. • The finally block will execute whether or not an exception is thrown. • This can be useful for closing file handles and freeing up any other Resources. • The finally clause is optional.
  • 27. Sample class FinallyDemo { // Through an exception out of the method. static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } }
  • 28. Java’s Built-in Exceptions • unchecked exceptions - because the compiler does not check to see if a method handles or throws these exceptions. • checked exceptions- Java defines several other types of exceptions that relate to its various class libraries
  • 31. Creating Your Own Exception Subclasses • To create your own exception types to handle situations specific to your applications, to do so just define a subclass of Exception.
  • 32. Sample class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } } class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")");
  • 33. if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }
  • 34. Chained Exceptions • The chained exception feature allows you to associate another exception with an exception.