SlideShare uma empresa Scribd logo
1 de 30
Souradeep Saha
Writayan Das
Exception Handling
Introduction What is an Exception?
An exception is an unexpected event that occurs during
runtime and causes normal program flow to be disrupted.
Some common examples:
 Divide by zero errors
 Accessing the elements of an array beyond its range
 Invalid input
 Hard disk crash
 Opening a non-existent file
 Heap memory exhaustion
Introduction Exception Handling
The way of handling anomalous situations in a program-run is
known as Exception Handling.
Its advantages are:
 Exception handling separates error-handling code from
normal code
 It clarifies the code and enhances readability
 It stimulates consequences as the error-handling takes
place at one place and in one manner
 It makes for clear, robust and fault-tolerant programs
1
• Write code such that it raises an error flag every
time something goes wrong
• [throw exception]
2
• Error flag is raised, then
3
• Call the Error-handling routine
• [catch exception]
Concept of Exception Handling
Exception An unexpected error that occurs during runtime
Throwing
The process by which an exception is generated and
passed to the program
Catching
Capturing an exception that has just occurred and
executing statements that try to resolve the problem
Catch
clause or
catch
block
The block of code that attempts to deal with the
exception
Stack
trace
The sequence of method calls that brought control to
the point where the exception occurred
Terminology
Java: Categories of Exception
Checked Exception
Checked exceptions are inherited from the core Java class Exception.
They represent exceptions that are frequently considered “non fatal” to
program execution
Checked exceptions must be handled in your code, or passed to parent
classes for handling
Unchecked Exception
Unchecked exceptions represent error conditions that are considered
“fatal” to program execution.
You do not have to do anything with an unchecked exception. Your
program will terminate with an appropriate error message
If the method contains code that may cause a checked
exception, we MUST handle the exception OR pass the
exception to the parent class (every class has Object as the
ultimate parent)
₪ To handle the exception, we write a “try-catch” block.
₪ To pass the exception “up the chain”, we declare a
throws clause in our method or class declaration.
How do we handle exceptions?
import java.io.*;
public class ExcepTest
{
public static void main(String args[])
{
try
{
int a[] = new int[2];
System.out.println("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
Java: Try-Catch MechanismWherever the code may trigger
an exception, the normal code
logic is placed inside a block of
code starting with the “try”
keyword:
After the try block, the code to
handle the exception should it
arise is placed in a block of
code starting with the
“catch” keyword.
try
{
//Protected code
}
catch(ExceptionType1 e1)
{
//Catch block
}
finally
{
//The finally block always executes.
}
finally keyword
The finally keyword is used to create a block of code that follows a try
block. A finally block of code always executes, whether or not an exception
has occurred.
Using a finally block allows you to run any cleanup-type statements that
you want to execute, no matter what happens in the protected code.
C++: General form of try and catch
try
{
// try block
}
catch (type1 arg)
{
// catch block
}
catch (type2 arg)
{
// catch block
}
catch (type3 arg)
{
// catch block
}
...
catch (typeN arg)
{
// catch block
}
Note: The try can be as
short as a few
statements within one
function or as all -
encompassing
as enclosing the main()
function code within a
try block.
The throw keyword
Note:
› If an exception is thrown for which there is no applicable catch statement, an
abnormal program termination may occur.
› Throwing an unhandled exception causes the standard library function terminate() to
be invoked.
› By default, terminate() calls abort() to stop the program, but we can specify our own
termination handler.
General Form:
throw exception;
— throw generates the exception specified by exception
— throw must be executed within a try block
— throw can also be executed within a function called from a try block
import java.io.*;
public class className
{
public void deposit(double amount)
throws Exception
{
// Method implementation
}
//Remainder of class definition
}
Java: Passing the Exception
In any method that
might throw an
exception, you may
declare the method as
“throws” that
exception, and thus
avoid handling the
exception yourself
Java Exception Hierarchy
Java: Creating Exceptions
class WordContainsException extends Exception
{
//Parameterless Constructor
public WordContainsException(){}
//Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
//Process message however you would like
}
Usage:
C++: A Simple Example
#include <iostream>
using namespace std;
int main()
{
cout << "Startn";
try
{ // start a try block
cout << "Inside try blockn";
throw 100; // throw an error
cout << "This will not execute";
}
catch (int i)
{ // catch an error
cout << "Caught an exception --
value is: ";
cout << i << "n";
}
cout << "End";
return 0;
}
Output:
Start
Inside try block
Caught an exception -
- value is: 100
End
(double i)
Output:
Start
Inside try block
Abnormal program
termination
#include <iostream>
using namespace std;
void Xtest(int test)
{
cout << "Inside Xtest, test is: " << test << "n";
if(test)
throw test;
}
int main()
{
cout << "Startn";
try
{
cout << "Inside try blockn";
Xtest(0);
Xtest(1);
Xtest(2);
}
catch (int i)
{
cout <<"Caught an exception -- value is: ";
cout << i << "n";
}
cout << "End";
return 0;
}
Output:
Start
Inside try block
Inside Xtest, test is: 0
Inside Xtest, test is: 1
Caught an exception --
value is: 1
End
C++: Throwing an exception from outside try block
Catching Class Types: An Example
#include <iostream>
#include <cstring>
using namespace std;
class MyException
{
public:
char str_what[80];
int what;
MyException()
{
*str_what = 0;
what =0;
}
MyException(char *s, int e)
{
strcpy(str_what, s);
what = e;
}
};
int main()
{
int i;
try
{
cout << "Enter a positive
number: ";
cin >> i;
if(i<0)
throw MyException("Not
Positive", i);
}
catch (MyException e)
{
cout << e.str_what << ": ";
cout << e.what << "n";
}
return 0;
}
Sample run:
Enter a positive
number: -4
Not Positive: -4
Handling Derived-Class Exceptions
#include <iostream>
using namespace std;
class B
{};
class D: public B
{};
int main()
{
D derived;
try
{
throw derived;
}
catch(B b)
{
cout << "Caught a base class.n";
}
catch(D d)
{
cout << "This won't execute.n";
}
return 0;
}
Note:
Here, because derived
is an object that has B
as a base class, it
will be caught by the
first catch clause and
the second clause will
never execute.
Some compilers will
flag this condition
with a warning message.
Others may issue an
error. Either way, to
fix this condition, we
should reverse the
order of the catch
clauses.
Exception Handling Options
There are several additional features and nuances to C++ exception handling that
make it easier and more convenient to use. These attributes are discussed here.
Catching All Exceptions
In some circumstances we want an exception
handler to catch all exceptions instead of just a
certain type.
This is easily accomplished by using this form of
catch:
catch(...)
{
// process all exceptions
}
Restricting Exceptions
A throw clause is added to a function definition to specify
which types of exceptions it can throw as shown below:
ret-type func-name(arg-list) throw(type-list)
{
//…
}
Note:
› only those data types contained in the comma-separated type-list may be thrown by
the function
› throwing any other type of expression will cause abnormal program termination
› if we don't want a function to be able to throw any exceptions, then we use an
empty list
Restricting Exceptions (continued…)
What happens when an unsupported exception is thrown?
Standard library function
unexpected() is called
By default, unexpected()
calls abort(), that
abnormally terminates the
program
However, we can specify our
own unexpected handler, as
discussed later.
Note:
⁻ a function can be
restricted only in what
types of exceptions it
throws back to the try
block that called it.
⁻ a try block within a
function may throw any
type of exception so
long as it is caught
within that function.
#include <iostream>
using namespace std;
void Xhandler()
{
try
{
throw "hello";
}
catch(const char *)
{
cout << "Caught char * inside
Xhandlern";
throw ;
}
}
int main()
{
cout << "Startn";
try
{
Xhandler();
}
catch(const char *)
{
cout << "Caught char * inside mainn";
}
cout << "End";
return 0;
}
Output:
Start
Caught char * inside
Xhandler
Caught char * inside main
End
C++: Rethrowing an exception
Note:
₪ this causes the current
exception to be passed on
to an outer try/catch
sequence
₪ when we rethrow an
exception, it will be caught
by the next catch statement
in the hierarchy
terminate() and unexpected()
void terminate() and void unexpected() are standard C++ library functions that are
called when something goes wrong during the process of exception handling.
Note:
₪ In general, terminate() is the handler of last resort when
no other handlers for an exception are available. By
default, terminate() calls abort().
terminate() is called in the following circumstances:
₪ whenever the exception handling subsystem fails to find
a matching catch statement for an exception.
₪ It is also called if our program attempts to rethrow an
exception when no exception was originally thrown.
₪ is also called under various other, more obscure
circumstances.
The unexpected() function
is called when a function
attempts to throw an
exception that is not
allowed by its throw list.
By default, unexpected()
calls terminate() .
Setting the Terminate and Unexpected Handlers
To change the terminate handler, we use set_terminate() , shown here:
terminate_handler set_terminate(terminate_handler newhandler) throw( );
Here, newhandler is a pointer to the new terminate handler. The function returns a pointer to
the old terminate handler. The new terminate handler must be of type
terminate_handler, which is defined like this:
typedef void (*terminate_handler) ( );
To change the unexpected handler, use set_unexpected() , shown here:
unexpected_handler set_unexpected(unexpected_handler newhandler) throw( );
Here, newhandler is a pointer to the new unexpected handler. The function returns a pointer
to the old unexpected handler. The new unexpected handler must be of type
unexpected_handler, which is defined like this:
typedef void (*unexpected_handler) ( );
#include <cstdlib>
#include <exception>
using namespace std;
void my_Thandler()
{
cout << "Inside new terminate handlern";
abort();
}
int main()
{
set_terminate(my_Thandler);
try
{
cout << "Inside try blockn";
throw 100;
}
catch (double i)
{}
return 0;
}
Output:
Inside try block
Inside new terminate
handler
abnormal program
termination
Example: Terminate handler
The uncaught_exception( ) Function
The C++ exception handling subsystem supplies one useful function:
uncaught_exception(). Its prototype is shown here:
bool uncaught_exception( );
This function returns true if an exception has been thrown but not yet caught. Once
caught, the function returns false.
The exception and bad_exception Classes
When a function supplied by the C++ standard library throws an exception, it will be
an object derived from the base class exception.
An object of the class bad_exception can be thrown by the unexpected handler.
These classes require the header <exception>.
Miscellaneous
Implementing in a program: An Example
#include <iostream>
using namespace std;
void divide(double a, double b);
int main()
{
double i, j;
do
{
cout << "Enter numerator
(0 to stop): ";
cin >> i;
cout << "Enter denominator: ";
cin >> j;
divide(i, j);
}
while(i != 0);
return 0;
}
void divide(double a, double b)
{
try
{
if(!b) throw b;
cout << "Result: " << a/b
<< endl;
}
catch (double b)
{
cout << "Result: Infinity";
}
}
Bibliography
C++: The Complete Reference.
Third Edition. Herbert Schildt
www.stackoverflow.com
Exception Handling

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java exception
Java exception Java exception
Java exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
6. static keyword
6. static keyword6. static keyword
6. static keyword
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception handling
Exception handling Exception handling
Exception handling
 

Semelhante a Exception Handling

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVARajan Shah
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Exception handling
Exception handlingException handling
Exception handlingWaqas Abbasi
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingAboMohammad10
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
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 in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 

Semelhante a Exception Handling (20)

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Mais de Reddhi Basu

Program and System Threats
Program and System ThreatsProgram and System Threats
Program and System ThreatsReddhi Basu
 
Software Engineering - Software Models
Software Engineering - Software ModelsSoftware Engineering - Software Models
Software Engineering - Software ModelsReddhi Basu
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++Reddhi Basu
 
Storage Class Specifiers
Storage Class SpecifiersStorage Class Specifiers
Storage Class SpecifiersReddhi Basu
 

Mais de Reddhi Basu (6)

Program and System Threats
Program and System ThreatsProgram and System Threats
Program and System Threats
 
Software Engineering - Software Models
Software Engineering - Software ModelsSoftware Engineering - Software Models
Software Engineering - Software Models
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
Storage Class Specifiers
Storage Class SpecifiersStorage Class Specifiers
Storage Class Specifiers
 
Big Data
Big DataBig Data
Big Data
 
System Security
System SecuritySystem Security
System Security
 

Último

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Exception Handling

  • 2. Introduction What is an Exception? An exception is an unexpected event that occurs during runtime and causes normal program flow to be disrupted. Some common examples:  Divide by zero errors  Accessing the elements of an array beyond its range  Invalid input  Hard disk crash  Opening a non-existent file  Heap memory exhaustion
  • 3. Introduction Exception Handling The way of handling anomalous situations in a program-run is known as Exception Handling. Its advantages are:  Exception handling separates error-handling code from normal code  It clarifies the code and enhances readability  It stimulates consequences as the error-handling takes place at one place and in one manner  It makes for clear, robust and fault-tolerant programs
  • 4. 1 • Write code such that it raises an error flag every time something goes wrong • [throw exception] 2 • Error flag is raised, then 3 • Call the Error-handling routine • [catch exception] Concept of Exception Handling
  • 5. Exception An unexpected error that occurs during runtime Throwing The process by which an exception is generated and passed to the program Catching Capturing an exception that has just occurred and executing statements that try to resolve the problem Catch clause or catch block The block of code that attempts to deal with the exception Stack trace The sequence of method calls that brought control to the point where the exception occurred Terminology
  • 6. Java: Categories of Exception Checked Exception Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program execution Checked exceptions must be handled in your code, or passed to parent classes for handling Unchecked Exception Unchecked exceptions represent error conditions that are considered “fatal” to program execution. You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message
  • 7. If the method contains code that may cause a checked exception, we MUST handle the exception OR pass the exception to the parent class (every class has Object as the ultimate parent) ₪ To handle the exception, we write a “try-catch” block. ₪ To pass the exception “up the chain”, we declare a throws clause in our method or class declaration. How do we handle exceptions?
  • 8. import java.io.*; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } Java: Try-Catch MechanismWherever the code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword.
  • 9. try { //Protected code } catch(ExceptionType1 e1) { //Catch block } finally { //The finally block always executes. } finally keyword The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code.
  • 10. C++: General form of try and catch try { // try block } catch (type1 arg) { // catch block } catch (type2 arg) { // catch block } catch (type3 arg) { // catch block } ... catch (typeN arg) { // catch block } Note: The try can be as short as a few statements within one function or as all - encompassing as enclosing the main() function code within a try block.
  • 11. The throw keyword Note: › If an exception is thrown for which there is no applicable catch statement, an abnormal program termination may occur. › Throwing an unhandled exception causes the standard library function terminate() to be invoked. › By default, terminate() calls abort() to stop the program, but we can specify our own termination handler. General Form: throw exception; — throw generates the exception specified by exception — throw must be executed within a try block — throw can also be executed within a function called from a try block
  • 12. import java.io.*; public class className { public void deposit(double amount) throws Exception { // Method implementation } //Remainder of class definition } Java: Passing the Exception In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself
  • 14. Java: Creating Exceptions class WordContainsException extends Exception { //Parameterless Constructor public WordContainsException(){} //Constructor that accepts a message public WordContainsException(String message) { super(message); } } try { if(word.contains(" ")) { throw new WordContainsException(); } } catch(WordContainsException ex) { //Process message however you would like } Usage:
  • 15. C++: A Simple Example #include <iostream> using namespace std; int main() { cout << "Startn"; try { // start a try block cout << "Inside try blockn"; throw 100; // throw an error cout << "This will not execute"; } catch (int i) { // catch an error cout << "Caught an exception -- value is: "; cout << i << "n"; } cout << "End"; return 0; } Output: Start Inside try block Caught an exception - - value is: 100 End (double i) Output: Start Inside try block Abnormal program termination
  • 16. #include <iostream> using namespace std; void Xtest(int test) { cout << "Inside Xtest, test is: " << test << "n"; if(test) throw test; } int main() { cout << "Startn"; try { cout << "Inside try blockn"; Xtest(0); Xtest(1); Xtest(2); } catch (int i) { cout <<"Caught an exception -- value is: "; cout << i << "n"; } cout << "End"; return 0; } Output: Start Inside try block Inside Xtest, test is: 0 Inside Xtest, test is: 1 Caught an exception -- value is: 1 End C++: Throwing an exception from outside try block
  • 17. Catching Class Types: An Example #include <iostream> #include <cstring> using namespace std; class MyException { public: char str_what[80]; int what; MyException() { *str_what = 0; what =0; } MyException(char *s, int e) { strcpy(str_what, s); what = e; } }; int main() { int i; try { cout << "Enter a positive number: "; cin >> i; if(i<0) throw MyException("Not Positive", i); } catch (MyException e) { cout << e.str_what << ": "; cout << e.what << "n"; } return 0; } Sample run: Enter a positive number: -4 Not Positive: -4
  • 18. Handling Derived-Class Exceptions #include <iostream> using namespace std; class B {}; class D: public B {}; int main() { D derived; try { throw derived; } catch(B b) { cout << "Caught a base class.n"; } catch(D d) { cout << "This won't execute.n"; } return 0; } Note: Here, because derived is an object that has B as a base class, it will be caught by the first catch clause and the second clause will never execute. Some compilers will flag this condition with a warning message. Others may issue an error. Either way, to fix this condition, we should reverse the order of the catch clauses.
  • 19. Exception Handling Options There are several additional features and nuances to C++ exception handling that make it easier and more convenient to use. These attributes are discussed here.
  • 20. Catching All Exceptions In some circumstances we want an exception handler to catch all exceptions instead of just a certain type. This is easily accomplished by using this form of catch: catch(...) { // process all exceptions }
  • 21. Restricting Exceptions A throw clause is added to a function definition to specify which types of exceptions it can throw as shown below: ret-type func-name(arg-list) throw(type-list) { //… } Note: › only those data types contained in the comma-separated type-list may be thrown by the function › throwing any other type of expression will cause abnormal program termination › if we don't want a function to be able to throw any exceptions, then we use an empty list
  • 22. Restricting Exceptions (continued…) What happens when an unsupported exception is thrown? Standard library function unexpected() is called By default, unexpected() calls abort(), that abnormally terminates the program However, we can specify our own unexpected handler, as discussed later. Note: ⁻ a function can be restricted only in what types of exceptions it throws back to the try block that called it. ⁻ a try block within a function may throw any type of exception so long as it is caught within that function.
  • 23. #include <iostream> using namespace std; void Xhandler() { try { throw "hello"; } catch(const char *) { cout << "Caught char * inside Xhandlern"; throw ; } } int main() { cout << "Startn"; try { Xhandler(); } catch(const char *) { cout << "Caught char * inside mainn"; } cout << "End"; return 0; } Output: Start Caught char * inside Xhandler Caught char * inside main End C++: Rethrowing an exception Note: ₪ this causes the current exception to be passed on to an outer try/catch sequence ₪ when we rethrow an exception, it will be caught by the next catch statement in the hierarchy
  • 24. terminate() and unexpected() void terminate() and void unexpected() are standard C++ library functions that are called when something goes wrong during the process of exception handling. Note: ₪ In general, terminate() is the handler of last resort when no other handlers for an exception are available. By default, terminate() calls abort(). terminate() is called in the following circumstances: ₪ whenever the exception handling subsystem fails to find a matching catch statement for an exception. ₪ It is also called if our program attempts to rethrow an exception when no exception was originally thrown. ₪ is also called under various other, more obscure circumstances. The unexpected() function is called when a function attempts to throw an exception that is not allowed by its throw list. By default, unexpected() calls terminate() .
  • 25. Setting the Terminate and Unexpected Handlers To change the terminate handler, we use set_terminate() , shown here: terminate_handler set_terminate(terminate_handler newhandler) throw( ); Here, newhandler is a pointer to the new terminate handler. The function returns a pointer to the old terminate handler. The new terminate handler must be of type terminate_handler, which is defined like this: typedef void (*terminate_handler) ( ); To change the unexpected handler, use set_unexpected() , shown here: unexpected_handler set_unexpected(unexpected_handler newhandler) throw( ); Here, newhandler is a pointer to the new unexpected handler. The function returns a pointer to the old unexpected handler. The new unexpected handler must be of type unexpected_handler, which is defined like this: typedef void (*unexpected_handler) ( );
  • 26. #include <cstdlib> #include <exception> using namespace std; void my_Thandler() { cout << "Inside new terminate handlern"; abort(); } int main() { set_terminate(my_Thandler); try { cout << "Inside try blockn"; throw 100; } catch (double i) {} return 0; } Output: Inside try block Inside new terminate handler abnormal program termination Example: Terminate handler
  • 27. The uncaught_exception( ) Function The C++ exception handling subsystem supplies one useful function: uncaught_exception(). Its prototype is shown here: bool uncaught_exception( ); This function returns true if an exception has been thrown but not yet caught. Once caught, the function returns false. The exception and bad_exception Classes When a function supplied by the C++ standard library throws an exception, it will be an object derived from the base class exception. An object of the class bad_exception can be thrown by the unexpected handler. These classes require the header <exception>. Miscellaneous
  • 28. Implementing in a program: An Example #include <iostream> using namespace std; void divide(double a, double b); int main() { double i, j; do { cout << "Enter numerator (0 to stop): "; cin >> i; cout << "Enter denominator: "; cin >> j; divide(i, j); } while(i != 0); return 0; } void divide(double a, double b) { try { if(!b) throw b; cout << "Result: " << a/b << endl; } catch (double b) { cout << "Result: Infinity"; } }
  • 29. Bibliography C++: The Complete Reference. Third Edition. Herbert Schildt www.stackoverflow.com

Notas do Editor

  1. This presentation demonstrates the new capabilities of PowerPoint and it is best viewed in Slide Show. These slides are designed to give you great ideas for the presentations you’ll create in PowerPoint 2010!For more sample templates, click the File tab, and then on the New tab, click Sample Templates.