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.
Ad

More Related Content

What's hot (13)

Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
priyankazope
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Abhishek Pachisia
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
Kumar
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
Pi j4.2 software-reliability
Pi j4.2 software-reliabilityPi j4.2 software-reliability
Pi j4.2 software-reliability
mcollison
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
priyankazope
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
Kumar
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
farhan amjad
 

Similar to Java exception handling (20)

Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Young Alista
 
Exception
ExceptionException
Exception
James Wong
 
Exception
ExceptionException
Exception
Luis Goldster
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Hoang Nguyen
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
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
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
JasmeetSingh326
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Unit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras UnivUnit-4 Java ppt for BCA Students Madras Univ
Unit-4 Java ppt for BCA Students Madras Univ
lavanyasujat1
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
happycocoman
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
Prabu U
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
DevaKumari Vijay
 
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
 
Ad

More from GaneshKumarKanthiah (11)

Software testing regression testing
Software testing  regression testingSoftware testing  regression testing
Software testing regression testing
GaneshKumarKanthiah
 
Software testing acceptance testing
Software testing  acceptance testingSoftware testing  acceptance testing
Software testing acceptance testing
GaneshKumarKanthiah
 
Software testing performance testing
Software testing  performance testingSoftware testing  performance testing
Software testing performance testing
GaneshKumarKanthiah
 
Software testing introduction
Software testing  introductionSoftware testing  introduction
Software testing introduction
GaneshKumarKanthiah
 
Java string handling
Java string handlingJava string handling
Java string handling
GaneshKumarKanthiah
 
Java packages
Java packagesJava packages
Java packages
GaneshKumarKanthiah
 
Java introduction
Java introductionJava introduction
Java introduction
GaneshKumarKanthiah
 
Java interface
Java interfaceJava interface
Java interface
GaneshKumarKanthiah
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
GaneshKumarKanthiah
 
Java awt
Java awtJava awt
Java awt
GaneshKumarKanthiah
 
Java applet
Java appletJava applet
Java applet
GaneshKumarKanthiah
 
Ad

Recently uploaded (20)

Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
Com fer un pla de gestió de dades amb l'eiNa DMP (en anglès)
CSUC - Consorci de Serveis Universitaris de Catalunya
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
How to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabberHow to Install & Activate ListGrabber - eGrabber
How to Install & Activate ListGrabber - eGrabber
eGrabber
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
fennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solutionfennec fox optimization algorithm for optimal solution
fennec fox optimization algorithm for optimal solution
shallal2
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptxDevOpsDays SLC - Platform Engineers are Product Managers.pptx
DevOpsDays SLC - Platform Engineers are Product Managers.pptx
Justin Reock
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...Transcript: Canadian book publishing: Insights from the latest salary survey ...
Transcript: Canadian book publishing: Insights from the latest salary survey ...
BookNet Canada
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 

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.
  翻译: