SlideShare a Scribd company logo
Exception Handling in java
Exceptions
Exception are such anomalous conditions
(or typically an event) which changes the
normal flow of execution of a program.
Exceptions are used for signaling
erroneous (exceptional) conditions which
occur during the run time processing.
Exceptions may occur in any
programming language.
Java Exception is an object that
describes an exceptional condition that
has occurred in a piece of code.
When exception takes place, an object
representing that condition is created
and thrown in the method that caused
the error. Then this exception is caught
and processed.
Advantages of exception handling
1. Exception provides the means to separate the details
of what to do when something out of the ordinary
happens from the main logic of a program.
2. With the help of this mechanism the working code
and the error-handling code can be disintegrated. It
also gives us the scope of organizing and
differentiating between different error types using a
separate block of codes. This is done with the help of
try-catch blocks.
3. Furthermore the errors can be propagated up the
method call stack i.e. problems occurring at the lower
level in the chain can be handled by the methods
higher up the call chain .
Types of Exceptions
Exception class is used for exceptional conditions that user
programs should catch. This is also the class that you will
subclass to create your own custom exception types. There
is an important subclass of Exception, called
RuntimeException. Exceptions of this type are
automatically defined for the programs that you write and
include things such as division by zero and invalid array
indexing.
Error class defines exceptions that are not expected to be
caught under normal circumstances by your program.
Exceptions of type Error are used by the Java run-time
system to indicate errors having to do with the run-time
environment, itself. Stack overflow is an example of such an
error.
Note: This chapter will not be dealing with exceptions of type Error,
because these are typically created in response to catastrophic
failures that cannot usually be handled by your program.
Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
Program statements that we want to monitor for
exceptions are contained within a try block. If an
exception occurs within the try block, it is
thrown. Our code can catch this exception
(using catch) and handle it in some rational
manner. System-generated exceptions are
automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword
throw. Any exception that is thrown out of a
method must be specified as such by a throws
clause. Any code that absolutely must be executed
before a method returns is put in a finally block.
This is the general form of an exception-handling block:
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
}
Here, ExceptionType is the type of exception that has
occurred.
Uncaught Exceptions
Before you learn how to handle exceptions in
your program, it is useful to see what happens
when you don’t handle them. This small
program includes an expression that
intentionally causes a divide-by-zero error.
class Exc
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}
When the Java run-time system detects the attempt to divide by
zero, it constructs a new exception object and then throws this
exception. This causes the execution of Exc to stop, because
once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately. In this example, we
haven’t supplied any exception handlers of our own, so the
exception is caught by the default handler provided by the Java
run-time system. Any exception that is not caught by your
program will ultimately be processed by the default handler. The
default handler displays a string describing the exception, prints a
stack trace from the point at which the exception occurred, and
terminates the program.
Here is the output generated when this example is executed.
java.lang.ArithmeticException: / by zero
at Exc.main(Exc0.java:4)
Using try and catch
Although the default exception handler
provided by the Java run-time system is
useful for debugging, we will usually
want to handle an exception yourself.
Doing so
provides two benefits.
First, it 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.
Immediately following the try
block, include a catch clause that
specifies the exception type that
you wish to catch.
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.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
Catch is not a function
Notice that the call to println( ) inside the try
block is never executed. Once an exception is
thrown, program control transfers out of the try
block into the catch block.
Put differently, catch is not “called,” so
execution never “returns” to the try block from
a catch. Thus, the line “This will not be printed.”
is not displayed. Once the catch statement has
executed, program control continues with the next
line in the program following the entire try/catch
mechanism.
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, we can specify two or more
catch clauses, each catching a different type of
exception. When an exception is thrown, each
catch statement is inspected in order, and the
first one whose type matches that of the
exception is executed. After one catch statement
executes, the others are bypassed, and
execution continues after the try/catch block.
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.");
}
}
This program will cause a division-by-zero exception if it is started with
no commandline parameters, since a will equal zero. It will survive the
division if you provide a command-line argument, setting a to
something larger than zero. But it will cause an
ArrayIndexOutOfBoundsException, since the int array c has a length of
1, yet the program attempts to assign a value to c[42].
Here is the output generated by running it both ways:
C:>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
C:>java MultiCatch TestArg
a = 1
Array index oob: java.lang.ArrayIndexOutOfBoundsException
After try/catch blocks.
Java’s Built-in Exceptions
Unchecked Exception
Unchecked Exception Meaning
Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an
incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a
method.
IllegalMonitorStateException Illegal monitor operation, such as
waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect
state.
IllegalThreadStateException Requested operation not compatible with
current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
Checked Exception
throws
If a method is capable of causing an exception that it does not
handle, it must specify this behavior 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. A throws clause lists the types of exceptions that
a method might throw. This is necessary for all exceptions,
except those of type Error or RuntimeException, or any of
their subclasses. All other exceptions that a method can throw
must be declared in the throws clause. If they are not, a
compile-time error will result.
This is the general form of a method declaration that includes a
throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a
method can throw.
Following is an example of an incorrect program
that tries to throw an exception that it does not
catch. Because the program does not specify a
throws clause to declare this fact, the program
will not compile.
// This program contains an error and will not compile.
class ThrowsDemo {
static void throwOne() {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
throwOne();
}
}
To make this example compile, you need to make two changes. First, you need
to declare that throwOne( ) throws IllegalAccessException. Second, main( )
must definea try/catch statement that catches this exception.
The corrected example is shown here:
// This is now correct.
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);
}
}
}
Here is the output generated by running this example program:
inside throwOne
caught java.lang.IllegalAccessException: demo
finally
When exceptions are thrown, execution in a method takes a rather abrupt,
nonlinear path that alters the normal flow through the method. Depending upon
how themethod is coded, it is even possible for an exception to cause the
method to return prematurely. This could be a problem in some methods. For
example, if a method opens a file upon entry and closes it upon exit, then you
will not want the code that closes the file to be bypassed by the exception-
handling mechanism. The finally keyword is designed to address this
contingency.
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. Any time a
method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also
executed just before the method returns. This can be useful for closing file
handles and freeing up any other resources that might have been allocated at
the beginning of a method with the intent of disposing of them before returning.
The finally clause is optional.
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");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return;
} finally {
System.out.println("procB's finally");
}
}
// Execute a try block normally.
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();
}
}
Here is the output generated by the preceding
program:
inside procA
procA’s finally
Exception caught
inside procB
procB’s finally
inside procC
procC’s finally
// This program creates a custom exception type.
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);
}
} }
OUTPUT
Called compute(1)
Normal exit
Called compute(20)
Caught MyException[20]
Ad

More Related Content

Similar to Exception Handling in java masters of computer application (20)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
SukhpreetSingh519414
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
Fraz Bakhsh
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 

Recently uploaded (20)

Web Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptx
Web Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptxWeb Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptx
Web Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptx
vinay salarite
 
science stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsjscience stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsj
prashantksistla
 
The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...
The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...
The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...
Gerald Fogel
 
Harmonizing Health_ Exploring Ayurveda's Holistic Approach.ppt
Harmonizing Health_ Exploring Ayurveda's Holistic Approach.pptHarmonizing Health_ Exploring Ayurveda's Holistic Approach.ppt
Harmonizing Health_ Exploring Ayurveda's Holistic Approach.ppt
Nimadia Holistic Counseling
 
International Organizations in Globalization by Slidesgo (1).pptx
International Organizations in Globalization by Slidesgo (1).pptxInternational Organizations in Globalization by Slidesgo (1).pptx
International Organizations in Globalization by Slidesgo (1).pptx
samanwaralakhly
 
LBE Presentation on Business Communication
LBE Presentation on Business CommunicationLBE Presentation on Business Communication
LBE Presentation on Business Communication
komal691665
 
1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf
1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf
1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf
govindbell
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
Bruce Bennett
 
美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)
美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)
美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)
Taqyea
 
essentialsoffreightforwarding-240429141915-bccde661 5.9.pptx
essentialsoffreightforwarding-240429141915-bccde661 5.9.pptxessentialsoffreightforwarding-240429141915-bccde661 5.9.pptx
essentialsoffreightforwarding-240429141915-bccde661 5.9.pptx
Sheldon Byron
 
Omar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim BiographyOmar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim Biography
Omar Selim
 
TSL_25_07_2024_exceltraining-190602234542.pptx
TSL_25_07_2024_exceltraining-190602234542.pptxTSL_25_07_2024_exceltraining-190602234542.pptx
TSL_25_07_2024_exceltraining-190602234542.pptx
ssuserbf85a1
 
Engineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptx
Engineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptxEngineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptx
Engineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptx
shilpijain263
 
Team Introduction slide for planing.pptx
Team Introduction slide for planing.pptxTeam Introduction slide for planing.pptx
Team Introduction slide for planing.pptx
maryanazir22
 
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa HagenUXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA Boston
 
NSS Quiz for vtu students in 2022 scheme
NSS Quiz for vtu students in 2022 schemeNSS Quiz for vtu students in 2022 scheme
NSS Quiz for vtu students in 2022 scheme
madhushreer21
 
Microsoft 365 Copilot - Vanderbilt University
Microsoft 365 Copilot - Vanderbilt UniversityMicrosoft 365 Copilot - Vanderbilt University
Microsoft 365 Copilot - Vanderbilt University
Neil Beyersdorf - MSES | CLSSMBB | Prosci OCM
 
Power BI Jobs in Jaipur – Top Career Options in Data Analytics.pptx
Power BI Jobs in Jaipur – Top Career Options in Data Analytics.pptxPower BI Jobs in Jaipur – Top Career Options in Data Analytics.pptx
Power BI Jobs in Jaipur – Top Career Options in Data Analytics.pptx
vinay salarite
 
Social Entrepreneurship (1) powerpoint.pptx
Social Entrepreneurship (1) powerpoint.pptxSocial Entrepreneurship (1) powerpoint.pptx
Social Entrepreneurship (1) powerpoint.pptx
kumaresan61999
 
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
Taqyea
 
Web Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptx
Web Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptxWeb Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptx
Web Developer Jobs in Jaipur for Freshers – Your Career Starts Here..pptx
vinay salarite
 
science stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsjscience stream ppt ankush.injcnjd jfcdsj
science stream ppt ankush.injcnjd jfcdsj
prashantksistla
 
The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...
The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...
The Public’s Messenger_ Why Press Information Officers Matter More Than Ever ...
Gerald Fogel
 
Harmonizing Health_ Exploring Ayurveda's Holistic Approach.ppt
Harmonizing Health_ Exploring Ayurveda's Holistic Approach.pptHarmonizing Health_ Exploring Ayurveda's Holistic Approach.ppt
Harmonizing Health_ Exploring Ayurveda's Holistic Approach.ppt
Nimadia Holistic Counseling
 
International Organizations in Globalization by Slidesgo (1).pptx
International Organizations in Globalization by Slidesgo (1).pptxInternational Organizations in Globalization by Slidesgo (1).pptx
International Organizations in Globalization by Slidesgo (1).pptx
samanwaralakhly
 
LBE Presentation on Business Communication
LBE Presentation on Business CommunicationLBE Presentation on Business Communication
LBE Presentation on Business Communication
komal691665
 
1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf
1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf
1Z0-771 - Oracle APEX Cloud Developer Professional (DUMPS).pdf
govindbell
 
Resumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying OnlineResumes, Cover Letters, and Applying Online
Resumes, Cover Letters, and Applying Online
Bruce Bennett
 
美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)
美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)
美国内布拉斯加大学科尼分校硕士毕业证学生卡(UNK官方成绩单)
Taqyea
 
essentialsoffreightforwarding-240429141915-bccde661 5.9.pptx
essentialsoffreightforwarding-240429141915-bccde661 5.9.pptxessentialsoffreightforwarding-240429141915-bccde661 5.9.pptx
essentialsoffreightforwarding-240429141915-bccde661 5.9.pptx
Sheldon Byron
 
Omar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim BiographyOmar Salim Biography Omar Salim Biography
Omar Salim Biography Omar Salim Biography
Omar Selim
 
TSL_25_07_2024_exceltraining-190602234542.pptx
TSL_25_07_2024_exceltraining-190602234542.pptxTSL_25_07_2024_exceltraining-190602234542.pptx
TSL_25_07_2024_exceltraining-190602234542.pptx
ssuserbf85a1
 
Engineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptx
Engineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptxEngineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptx
Engineering-Excellence-Top-BEBTech-Colleges-in-Delhi-2025 (1).pptx
shilpijain263
 
Team Introduction slide for planing.pptx
Team Introduction slide for planing.pptxTeam Introduction slide for planing.pptx
Team Introduction slide for planing.pptx
maryanazir22
 
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa HagenUXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA2025-dont-hate-job by Ira F. Cummings & Lisa Hagen
UXPA Boston
 
NSS Quiz for vtu students in 2022 scheme
NSS Quiz for vtu students in 2022 schemeNSS Quiz for vtu students in 2022 scheme
NSS Quiz for vtu students in 2022 scheme
madhushreer21
 
Power BI Jobs in Jaipur – Top Career Options in Data Analytics.pptx
Power BI Jobs in Jaipur – Top Career Options in Data Analytics.pptxPower BI Jobs in Jaipur – Top Career Options in Data Analytics.pptx
Power BI Jobs in Jaipur – Top Career Options in Data Analytics.pptx
vinay salarite
 
Social Entrepreneurship (1) powerpoint.pptx
Social Entrepreneurship (1) powerpoint.pptxSocial Entrepreneurship (1) powerpoint.pptx
Social Entrepreneurship (1) powerpoint.pptx
kumaresan61999
 
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
最新版加拿大特伦特大学毕业证(Trent毕业证书)原版定制
Taqyea
 
Ad

Exception Handling in java masters of computer application

  • 2. Exceptions Exception are such anomalous conditions (or typically an event) which changes the normal flow of execution of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Exceptions may occur in any programming language.
  • 3. Java Exception is an object that describes an exceptional condition that has occurred in a piece of code. When exception takes place, an object representing that condition is created and thrown in the method that caused the error. Then this exception is caught and processed.
  • 4. Advantages of exception handling 1. Exception provides the means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. 2. With the help of this mechanism the working code and the error-handling code can be disintegrated. It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks. 3. Furthermore the errors can be propagated up the method call stack i.e. problems occurring at the lower level in the chain can be handled by the methods higher up the call chain .
  • 6. Exception class is used for exceptional conditions that user programs should catch. This is also the class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. Error class defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error. Note: This chapter will not be dealing with exceptions of type Error, because these are typically created in response to catastrophic failures that cannot usually be handled by your program.
  • 7. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Program statements that we want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Our code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed before a method returns is put in a finally block.
  • 8. This is the general form of an exception-handling block: 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 } Here, ExceptionType is the type of exception that has occurred.
  • 9. Uncaught Exceptions Before you learn how to handle exceptions in your program, it is useful to see what happens when you don’t handle them. This small program includes an expression that intentionally causes a divide-by-zero error. class Exc { public static void main(String args[]) { int d = 0; int a = 42 / d; } }
  • 10. When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. Here is the output generated when this example is executed. java.lang.ArithmeticException: / by zero at Exc.main(Exc0.java:4)
  • 11. Using try and catch Although the default exception handler provided by the Java run-time system is useful for debugging, we will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating.
  • 12. To guard against and handle a run- time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch.
  • 13. 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."); } } This program generates the following output: Division by zero. After catch statement.
  • 14. Catch is not a function Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
  • 15. 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, we can specify two or more catch clauses, each catching a different type of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block.
  • 16. 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."); } }
  • 17. This program will cause a division-by-zero exception if it is started with no commandline parameters, since a will equal zero. It will survive the division if you provide a command-line argument, setting a to something larger than zero. But it will cause an ArrayIndexOutOfBoundsException, since the int array c has a length of 1, yet the program attempts to assign a value to c[42]. Here is the output generated by running it both ways: C:>java MultiCatch a = 0 Divide by 0: java.lang.ArithmeticException: / by zero After try/catch blocks. C:>java MultiCatch TestArg a = 1 Array index oob: java.lang.ArrayIndexOutOfBoundsException After try/catch blocks.
  • 18. Java’s Built-in Exceptions Unchecked Exception Unchecked Exception Meaning Meaning ArithmeticException Arithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsException Array index is out-of-bounds. ArrayStoreException Assignment to an array element of an incompatible type. ClassCastException Invalid cast. IllegalArgumentException Illegal argument used to invoke a method. IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread. IllegalStateException Environment or application is in incorrect state. IllegalThreadStateException Requested operation not compatible with current thread state. IndexOutOfBoundsException Some type of index is out-of-bounds. NegativeArraySizeException Array created with a negative size.
  • 20. throws If a method is capable of causing an exception that it does not handle, it must specify this behavior 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. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause. If they are not, a compile-time error will result. This is the general form of a method declaration that includes a throws clause: type method-name(parameter-list) throws exception-list { // body of method } Here, exception-list is a comma-separated list of the exceptions that a method can throw.
  • 21. Following is an example of an incorrect program that tries to throw an exception that it does not catch. Because the program does not specify a throws clause to declare this fact, the program will not compile. // This program contains an error and will not compile. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } }
  • 22. To make this example compile, you need to make two changes. First, you need to declare that throwOne( ) throws IllegalAccessException. Second, main( ) must definea try/catch statement that catches this exception. The corrected example is shown here: // This is now correct. 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); } } } Here is the output generated by running this example program: inside throwOne caught java.lang.IllegalAccessException: demo
  • 23. finally When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method. Depending upon how themethod is coded, it is even possible for an exception to cause the method to return prematurely. This could be a problem in some methods. For example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the exception- handling mechanism. The finally keyword is designed to address this contingency. 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. Any time a method is about to return to the caller from inside a try/catch block, via an uncaught exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional.
  • 24. 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"); } } // Return from within a try block. static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } } // Execute a try block normally.
  • 25. 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(); } }
  • 26. Here is the output generated by the preceding program: inside procA procA’s finally Exception caught inside procB procB’s finally inside procC procC’s finally
  • 27. // This program creates a custom exception type. class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } }
  • 28. 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); } } }
  • 29. OUTPUT Called compute(1) Normal exit Called compute(20) Caught MyException[20]
  翻译: