SlideShare uma empresa Scribd logo
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

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
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++
Janki Shah
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
VINOTH R
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
Harshal Misalkar
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
Sujan Mia
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in JavaAbhilash Nair
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 

Mais procurados (20)

Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
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 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++
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Introduction to method overloading &amp; method overriding in java hdm
Introduction to method overloading &amp; method overriding  in java  hdmIntroduction to method overloading &amp; method overriding  in java  hdm
Introduction to method overloading &amp; method overriding in java hdm
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Abstract class in c++
Abstract class in c++Abstract class in c++
Abstract class in c++
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 

Semelhante a Exception Handling

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
Rajan Shah
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Exception handling
Exception handlingException handling
Exception handling
Waqas Abbasi
 
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 Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
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
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
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.pptx
Nagaraju Pamarthi
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 

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
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

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 Models
Reddhi 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 Specifiers
Reddhi Basu
 
System Security
System SecuritySystem Security
System Security
Reddhi 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

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 

Último (20)

Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.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.