SlideShare a Scribd company logo
1
Exception Types – Uncaught Exceptions –
Using Try Catch – Multiple Catch – Nested Try
– throw- throws- finally – Built in Exceptions-
Using Exceptions
2
Error
 Successful execution of a program is very rare in
the first attempt.
 Mistakes may occur in development or while
typing a program.
 A mistake may lead to an error.
 An error
 may cause the program to produce unexpected
results.
 may terminate the execution of a program.
 may cause the system to crash.
 So the errors has to be detected and handled
properly.
3
Types of Errors
 Compile-time errors
 Run-time errors
4
 Errors detected during compile time.
 All syntax errors will be detected and
displayed by the Java compiler.
 .class file will not be created if the compiler
detects errors.
 Java compiler also tells us where the errors
are in the program.
 A single error may be the source of multiple
errors.
 Most of the compile time errors are due to
typing mistakes.
5
Example
class Example {
public static void main(String args[])
{
System.out.println("This is a simple Java
program.")
// Missing ;
}
} So while compiling, it will result in an error
Example.java:6: ';' expected
}
^
1 error
6
 Missing semicolons
 Missing brackets in classes and methods
 Misspelling of identifiers and keywords
 Missing double quotes in strings
 Use of undeclared variables
 Incompatible types in assignments / initialization
 Use of = in place of == operator
 Errors related to directory paths
 ‘javac’ is not recognized as an internal or external command,
operable program or batch file.
 Path must include the directory where the java executables
are stored.

7
 Errors detected during run time.
 .class files may be created as a result of
successful compilation.
 But the program may result in incorrect
output due to wrong logic or the program
may terminate due to errors such as stack
overflow.
 When run-time error occurs, Java run-time
generates an error condition and causes the
program to stop after displaying the
appropriate message.

8
Example
class Example
{
public static void main(String args[]) {
int a = 10;
int b = 0;
int c = a/b;
System.out.println(c); }
}
So while compiling, it will not result in an error. But while
running, it will result in the following error.
Exception in thread "main" java.lang.ArithmeticException: / by
zero
at Example.main(Example.java:7)
9
 Dividing an integer by zero
 Accessing an element that is out of the
bounds of an array
 Trying to store a value into an array of
incompatible class or type
 Passing a parameter that is not in a valid
range or value for a method
10
 An exception is an abnormal condition that
arises in a code sequence at run time.
 An exception is caused by a run-time error.
 When Java interpreter encounters an error,
it creates an exception object and throws it.
 If the exception object is not caught and
handled properly, the interpreter will
display an error message and terminate the
program.
11
 A Java exception is an object that describes an
exceptional (that is, error) condition that has occurred
in a piece of code.
 When an exceptional condition arises, an object
representing that exception is created and thrown in
the method that caused the error.
 That method may choose to handle the exception
itself, or pass it on.
 Either way, at some point, the exception is caught and
processed.
 Exceptions can be generated by the Java run-time
system, or they can be manually generated by your
code.
12
When a program throws an exception, it comes
to a stop. This exception should be caught by
exception handler and dealt with immediately. If
there is no default java runtime system provides
default handlers. This displays a string, which
describes the exception and the point.
13
14
// Usage of default exception handler
Class DefException {
public static void main(String srgs[]) {
int i[]={2};
i[10]=20;
}
}
It tries to set the value to the tenth element of the
integer array, which generates
ArrayIndexOutOfBoundsException.
Output
Java.lang. ArrayIndexOutOfBoundsException : 10
15
 Java exception handling is managed via five keywords:
 try
Program statements that needs to be monitored for
exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown.
 Catch
To catch the exception (using catch) thrown.
 Throw
System-generated exceptions are automatically thrown
by the Java run-time system.
 To manually throw an exception, use the keyword throw.
 Throws
 Any exception that is thrown out of a method must be
specified as such by a throws clause. finally
 Any code that absolutely must be executed before a method returns is
put in a finally block.
16
General Form:
try
{
// block of code to monitor for errors
}
catch (ExceptionType exOb)
{
// exception handler for ExceptionType1
}
// ...
finally
{
// block of code to be executed before try block ends
}
ExceptionType is the type of exception that has occurred
17
 All exception types are subclasses of the built-in
class Throwable, at the top of the exception class
hierarchy.
 Immediately below Throwable are two subclasses
that partition exceptions into two distinct
branches.
 1. Exception: This class is used for exceptional
conditions that user programs should catch,
important subclass of Exception, is
RuntimeException
 2. Error: defines exceptions that are not expected
to be caught under normal circumstances by
user program.
18
19
 Although the default exception handler provided by the Java
run-time system is useful for debugging, exception should be
handled by the user program.
 Two benefits:
 It allows you to fix the error.
 It prevents the program from automatically terminating.
 To guard against and handle a run-time error, simply enclose
the code that needs to be monitored inside a try block.
 Immediately following the try block, include a catch clause
that specifies the exception type that you wish to catch.
 The try block can have one or more statements that could
generate an exception.
 If any one statement that generates an exception, the
remaining statements in the block are skipped and execution
jumps to the catch block that is placed next to the try block.
20
class Ex {
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.
21
 // Usage of try and catch block
class NegTest{
public static void main(String args[]) {
try
{ // monitor a block of code.
Int arr[]=new int[-2];
System.out.println("first element :”+arr[0]);
}
Catch(NegativeArraySizeException n)
{
System.out.println("Generated Exception :” +n);
}
System.out.println("after the try block”);
}
}
Output:
This tries to print the first element in the array arr that is created. Since the array declaration
as negative, an exception is generated.
Generated Exception : java.lang.NegativeSizeArrayException
After the try block.
22
Multiple catch statements are required in the
program when more than one exception is
generated by a program. These catch statements
are searched by the exception thrown in order, and
the first one whose type matches that of the
exception is executed. Finally, if the exception does
not find a matching catch clause, it is passed onto
the default handler.
23
class MultiCatch {
public static void main(String args[ ]){
try
{
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
24
int c[ ] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index: " + e);
}
System.out.println("After try/catch.");
}}
25
Output:
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch.
C:>java MultiCatch TestArg
a = 1
Array index :
java.lang.ArrayIndexOutOfBoundsException
After try/catch.
26
// The try statement can be nested.
class NestTry {
public static void main(String args[]) {
try
{
int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
27
try
{ // nested try block
if(a == 1)
a = a / (a - a); // division by 0
if(a == 2)
{
int c[ ] = { 1 };
c[42] = 99; // out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index outofbounds: " + e);
}
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0: " + e);
}
}}
28
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
29
class Throws {
static void throwOne( ) throws
IllegalAccessException
{
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
30
public static void main(String args[ ]) {
try
{
throwOne();
}
catch (IllegalAccessException e)
{
System.out.println("Caught " + e);
}
}}
Note:
// A throws clause lists
 the types of exceptions that a method might throw.
31
OUTPUT:
inside throwOne
caught java.lang.IllegalAccess Exception:
demo
32
 finally creates a block of code that will be
executed after a try/catch block has
completed and before the code following
the try/catch block.
 The finally block will execute whether or
not an exception is thrown. If an exception
is thrown, the finally block will execute
even if no catch statement matches the
exception.
 The finally clause is optional.
33
class FinallyDemo {
static void procA( ) {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}}
34
static void procB() {
try {
System.out.println("inside procB");
return;
}
finally {
System.out.println("procB's finally");
}}
35
static void procC() {
try {
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}}
public static void main(String args[ ]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}}
36
OUTPUT:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
37

More Related Content

PPTX
Java exception handling
PPTX
Java exception handling
PPT
Java exception
PPTX
Chap2 exception handling
PPTX
Java - Exception Handling
PPTX
Exception handling in java
PPT
Java: Exception
PPTX
Interface andexceptions
Java exception handling
Java exception handling
Java exception
Chap2 exception handling
Java - Exception Handling
Exception handling in java
Java: Exception
Interface andexceptions

What's hot (20)

PPTX
Exception handling
PPT
Exception handling
PPTX
130410107010 exception handling
PPTX
Exception handling in Java
PPTX
Exception Handling
PPT
Exception Handling in JAVA
PPTX
Exception Handling in Java
PPTX
Exception handling in java
PPT
Exception handling
PDF
Built in exceptions
PPTX
Exception handling in java
PPTX
Exception handling in Java
PPT
exception handling
PPTX
L14 exception handling
PPT
Exception handling
PPT
12 exception handling
PPSX
Exception Handling
PDF
Best Practices in Exception Handling
PPT
PDF
javaexceptions
Exception handling
Exception handling
130410107010 exception handling
Exception handling in Java
Exception Handling
Exception Handling in JAVA
Exception Handling in Java
Exception handling in java
Exception handling
Built in exceptions
Exception handling in java
Exception handling in Java
exception handling
L14 exception handling
Exception handling
12 exception handling
Exception Handling
Best Practices in Exception Handling
javaexceptions
Ad

Similar to Exception handling in java (20)

PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPT
Exception
PPTX
Exception handling, Stream Classes, Multithread Programming
PPTX
Unit-4 Java ppt for BCA Students Madras Univ
PPT
Exception Handling Exception Handling Exception Handling
PPTX
Java-Unit 3- Chap2 exception handling
DOCX
MODULE5_EXCEPTION HANDLING.docx
PPTX
Exception Handling.pptx
PPT
8.Exception handling latest(MB).ppt .
PPT
Exception Handling in java masters of computer application
PPTX
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPTX
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception
Exception handling, Stream Classes, Multithread Programming
Unit-4 Java ppt for BCA Students Madras Univ
Exception Handling Exception Handling Exception Handling
Java-Unit 3- Chap2 exception handling
MODULE5_EXCEPTION HANDLING.docx
Exception Handling.pptx
8.Exception handling latest(MB).ppt .
Exception Handling in java masters of computer application
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
unit 4 msbte syallbus for sem 4 2024-2025
OBJECT ORIENTED PROGRAMMING_Unit3_NOTES first half.pptx
Ad

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
Cloud computing and distributed systems.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
MYSQL Presentation for SQL database connectivity
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
A comparative analysis of optical character recognition models for extracting...
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
Machine learning based COVID-19 study performance prediction
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Encapsulation theory and applications.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
The AUB Centre for AI in Media Proposal.docx
Mobile App Security Testing_ A Comprehensive Guide.pdf
Cloud computing and distributed systems.
Per capita expenditure prediction using model stacking based on satellite ima...
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
“AI and Expert System Decision Support & Business Intelligence Systems”
MYSQL Presentation for SQL database connectivity
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
A comparative analysis of optical character recognition models for extracting...
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectroscopy.pptx food analysis technology
Review of recent advances in non-invasive hemoglobin estimation
Spectral efficient network and resource selection model in 5G networks
NewMind AI Weekly Chronicles - August'25-Week II
Machine learning based COVID-19 study performance prediction
The Rise and Fall of 3GPP – Time for a Sabbatical?
Programs and apps: productivity, graphics, security and other tools
Encapsulation theory and applications.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...

Exception handling in java

  • 1. 1
  • 2. Exception Types – Uncaught Exceptions – Using Try Catch – Multiple Catch – Nested Try – throw- throws- finally – Built in Exceptions- Using Exceptions 2
  • 3. Error  Successful execution of a program is very rare in the first attempt.  Mistakes may occur in development or while typing a program.  A mistake may lead to an error.  An error  may cause the program to produce unexpected results.  may terminate the execution of a program.  may cause the system to crash.  So the errors has to be detected and handled properly. 3
  • 4. Types of Errors  Compile-time errors  Run-time errors 4
  • 5.  Errors detected during compile time.  All syntax errors will be detected and displayed by the Java compiler.  .class file will not be created if the compiler detects errors.  Java compiler also tells us where the errors are in the program.  A single error may be the source of multiple errors.  Most of the compile time errors are due to typing mistakes. 5
  • 6. Example class Example { public static void main(String args[]) { System.out.println("This is a simple Java program.") // Missing ; } } So while compiling, it will result in an error Example.java:6: ';' expected } ^ 1 error 6
  • 7.  Missing semicolons  Missing brackets in classes and methods  Misspelling of identifiers and keywords  Missing double quotes in strings  Use of undeclared variables  Incompatible types in assignments / initialization  Use of = in place of == operator  Errors related to directory paths  ‘javac’ is not recognized as an internal or external command, operable program or batch file.  Path must include the directory where the java executables are stored.  7
  • 8.  Errors detected during run time.  .class files may be created as a result of successful compilation.  But the program may result in incorrect output due to wrong logic or the program may terminate due to errors such as stack overflow.  When run-time error occurs, Java run-time generates an error condition and causes the program to stop after displaying the appropriate message.  8
  • 9. Example class Example { public static void main(String args[]) { int a = 10; int b = 0; int c = a/b; System.out.println(c); } } So while compiling, it will not result in an error. But while running, it will result in the following error. Exception in thread "main" java.lang.ArithmeticException: / by zero at Example.main(Example.java:7) 9
  • 10.  Dividing an integer by zero  Accessing an element that is out of the bounds of an array  Trying to store a value into an array of incompatible class or type  Passing a parameter that is not in a valid range or value for a method 10
  • 11.  An exception is an abnormal condition that arises in a code sequence at run time.  An exception is caused by a run-time error.  When Java interpreter encounters an error, it creates an exception object and throws it.  If the exception object is not caught and handled properly, the interpreter will display an error message and terminate the program. 11
  • 12.  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code.  When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.  That method may choose to handle the exception itself, or pass it on.  Either way, at some point, the exception is caught and processed.  Exceptions can be generated by the Java run-time system, or they can be manually generated by your code. 12
  • 13. When a program throws an exception, it comes to a stop. This exception should be caught by exception handler and dealt with immediately. If there is no default java runtime system provides default handlers. This displays a string, which describes the exception and the point. 13
  • 14. 14
  • 15. // Usage of default exception handler Class DefException { public static void main(String srgs[]) { int i[]={2}; i[10]=20; } } It tries to set the value to the tenth element of the integer array, which generates ArrayIndexOutOfBoundsException. Output Java.lang. ArrayIndexOutOfBoundsException : 10 15
  • 16.  Java exception handling is managed via five keywords:  try Program statements that needs to be monitored for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown.  Catch To catch the exception (using catch) thrown.  Throw System-generated exceptions are automatically thrown by the Java run-time system.  To manually throw an exception, use the keyword throw.  Throws  Any exception that is thrown out of a method must be specified as such by a throws clause. finally  Any code that absolutely must be executed before a method returns is put in a finally block. 16
  • 17. General Form: try { // block of code to monitor for errors } catch (ExceptionType exOb) { // exception handler for ExceptionType1 } // ... finally { // block of code to be executed before try block ends } ExceptionType is the type of exception that has occurred 17
  • 18.  All exception types are subclasses of the built-in class Throwable, at the top of the exception class hierarchy.  Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.  1. Exception: This class is used for exceptional conditions that user programs should catch, important subclass of Exception, is RuntimeException  2. Error: defines exceptions that are not expected to be caught under normal circumstances by user program. 18
  • 19. 19
  • 20.  Although the default exception handler provided by the Java run-time system is useful for debugging, exception should be handled by the user program.  Two benefits:  It allows you to fix the error.  It prevents the program from automatically terminating.  To guard against and handle a run-time error, simply enclose the code that needs to be monitored inside a try block.  Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.  The try block can have one or more statements that could generate an exception.  If any one statement that generates an exception, the remaining statements in the block are skipped and execution jumps to the catch block that is placed next to the try block. 20
  • 21. class Ex { 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. 21
  • 22.  // Usage of try and catch block class NegTest{ public static void main(String args[]) { try { // monitor a block of code. Int arr[]=new int[-2]; System.out.println("first element :”+arr[0]); } Catch(NegativeArraySizeException n) { System.out.println("Generated Exception :” +n); } System.out.println("after the try block”); } } Output: This tries to print the first element in the array arr that is created. Since the array declaration as negative, an exception is generated. Generated Exception : java.lang.NegativeSizeArrayException After the try block. 22
  • 23. Multiple catch statements are required in the program when more than one exception is generated by a program. These catch statements are searched by the exception thrown in order, and the first one whose type matches that of the exception is executed. Finally, if the exception does not find a matching catch clause, it is passed onto the default handler. 23
  • 24. class MultiCatch { public static void main(String args[ ]){ try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; 24
  • 25. int c[ ] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index: " + e); } System.out.println("After try/catch."); }} 25
  • 26. Output: C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch. C:>java MultiCatch TestArg a = 1 Array index : java.lang.ArrayIndexOutOfBoundsException After try/catch. 26
  • 27. // The try statement can be nested. class NestTry { public static void main(String args[]) { try { int a = args.length; int b = 42 / a; System.out.println("a = " + a); 27
  • 28. try { // nested try block if(a == 1) a = a / (a - a); // division by 0 if(a == 2) { int c[ ] = { 1 }; c[42] = 99; // out-of-bounds exception } } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index outofbounds: " + e); } } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } }} 28
  • 29. 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 29
  • 30. class Throws { static void throwOne( ) throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } 30
  • 31. public static void main(String args[ ]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } }} Note: // A throws clause lists  the types of exceptions that a method might throw. 31
  • 33.  finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.  The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception.  The finally clause is optional. 33
  • 34. class FinallyDemo { static void procA( ) { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); }} 34
  • 35. static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); }} 35
  • 36. static void procC() { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); }} public static void main(String args[ ]) { try { procA(); } catch (Exception e) { System.out.println("Exception caught"); } procB(); procC(); }} 36
  • 37. OUTPUT: inside procA procA’s finally Exception caught inside procB procB’s finally inside procC procC’s finally 37