SlideShare a Scribd company logo
EXCEPTIONS
WHAT IS AN EXCEPTION?
An exception is an error condition or unexpected behavior encountered by
an executing program during runtime. In fact the name exception comes
from the fact that although a problem can occur; the problem occurs
infrequently.
Trapping and handling of runtime errors is one of the most crucial tasks
ahead of any programmer.As a developer, you sometimes seem to spend
more time checking for errors and handling them than you do on the core
logic of the actual program.You can address this issue by using system
exceptions that are designed for the purpose of handling errors. In this
article, you will learn how to catch and handle exceptions in C#.
EXCEPTIONS
o The C# language's exception handling features provide a
way to deal with any unexpected or exceptional situations
that arise while a program is running.
o Exception handling uses the try, catch, and finally
keywords to attempt actions that may not succeed, to
handle failures, and to clean up resources afterwards.
EXCEPTIONS
The .NET base class libraries define numerous exceptions such as
o FormatException
o IndexOutOfRangeException
o FileNotFoundException
o ArgumentOutOfRangeException
.NET platform provides a standard technique to
send and trap runtime errors: structured exception handling (SEH).
THE ATOMS OF .NET
EXCEPTION HANDLING
o Programming with structured exception handling
o involves the use of four interrelated entities:
o A class type that represents the details of the exception
that occurred
o A member that throws an instance of the exception class to
the caller
o A block of code on the caller’s side that invokes the
exception-prone member
o A block of code on the caller’s side that will process (or
catch) the exception should it occur
WHAT ARETHE OTHER
EXCEPTION CLASSES?
Here's a list of few Common Exception Classes:
o System.ArithmeticException-A base class for exceptions that occur during arithmetic
operations, such as System.DivideByZeroException
o System.ArrayTypeMismatchException-Thrown when a store into an array fails because
the actual type of the stored element is incompatible with the actual type of the array.
o System.DivideByZeroException-Thrown when an attempt to divide an integral value by
zero occurs.
o System.IndexOutOfRangeException-Thrown when an attempt to index an array via an
index that is less than zero or outside the bounds of the array.
WHAT ARETHE OTHER
EXCEPTION CLASSES?
o System.InvalidCastExceptionThrown when an explicit conversion from a
base type or interface to derived types fails at run time.
o System.MulticastNotSupportedException-Thrown when an attempt to
combine two non-null delegates fails, because the delegate type does not
have a void return type.
o System.NullReferenceException-Thrown when a null reference is used in
a way that causes the referenced object to be required.
o System.OutOfMemoryException-Thrown when an attempt to allocate
memory (via new) fails.
o System.OverflowException-Thrown when an arithmetic operation in a
checked context overflows.
EXCEPTIONS OVERVIEW
o When your application encounters an exceptional circumstance, such as a
division by zero or low memory warning, an exception is generated.
o Once an exception occurs, the flow of control immediately jumps to an
associated exception handler, if one is present.
o If no exception handler for a given exception is present, the program stops
executing with an error message.
o Actions that may result in an exception are executed with the try keyword.
o An exception handler is a block of code that is executed when an exception
occurs. In C#, the catch keyword is used to define an exception handler.
o Exceptions can be explicitly generated by a program using the throw keyword.
o Exception objects contain detailed information about the error, including the
state of the call stack and a text description of the error.
o Code in a finally block is executed even if an exception is thrown, thus
allowing a program to release resources.
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[2];
numbers[0] = 23;
numbers[1] = 32;
numbers[2] = 42;
foreach(int i in numbers)
Console.WriteLine(i);
Console.ReadLine();
}
}
WHAT IS EXCEPTION HANDLING
ANDWHY DOWE NEED IT?
o The mark of a good, robust program is planning for the unexpected,
and recovering if it does happen. Errors can happen at almost any time
during the compilation or execution of a program.
o We can detect and deal with these errors using Exception Handling.
Exception handling is an in built mechanism in .NET framework to
detect and handle run time errors.
o At the heart of the .NET Framework is the Common Language
Runtime (CLR) which in addition to acting as a virtual machine and
interpreting and executing IL code on the fly, performs numerous
other functions such as type safety checking, memory management,
garbage collection and Exception handling.
WHAT IS EXCEPTION HANDLING
ANDWHY DOWE NEED IT?
o The .NET framework contains lots of standard exceptions.
It allows you to define how the system reacts in
unexpected situations like 'File not found' , 'Out of
Memory' , bad logic, non-availability of operating system
resources other than memory, 'Index out of bounds' and
so on.
o When the code which has a problem, is executed, it 'raises
an exception'. If a programmer does not provide a
mechanism to handle these anomalies, the .NET run time
environment provides a default mechanism, which
terminates the program execution.This mechanism is a
structured exception handling mechanism.
try
{
// this code may cause an exception.
// If it does cause an exception, the execution will not continue.
// Instead,it will jump to the 'catch' block.
}
catch (Exception ex)
{
// I get executed when an exception occurs in the try block.
// Write the error handling code here.
}
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[2];
try
{
numbers[0] = 23;
numbers[1] = 32;
numbers[2] = 42;
foreach(int i in numbers)
Console.WriteLine(i);
}
catch
{
Console.WriteLine("Something went wrong!");
}
Console.ReadLine();
}
}
catch(Exception ex)
{
Console.WriteLine("An error occured: " + ex.Message);
}
o Exception is the most general type of exception.The rules of exception
handling tells us that we should always use the least general type of exception,
and in this case, we actually know the exact type of exception generated by
our code. How? BecauseVisual Studio told us when we didn't handle it. If
you're in doubt, the documentation usually describes which exception(s) a
method may throw.Another way of finding out is using the Exception class to
tell us - change the output line to this:
o Console.WriteLine("An error occured: " + ex.GetType().ToString());
o The result is, as expected, IndexOutOfRangeException.We should therefore handle
this exception, but nothing prevents us from handling more than one exception. In
some situations you might wish to do different things, depending on which exception
was thrown.
catch(IndexOutOfRangeException ex)
{
Console.WriteLine("An index was out of range!");
}
catch(Exception ex)
{
Console.WriteLine("Some sort of error occured: " +
ex.Message);
}
OK, BUT WHAT ABOUTTHE
FINALLY BLOCK?
o C# provides the finally block to enclose a set of statements that need
to be executed regardless of the course of control flow. So as a result
of normal execution, if the control flow reaches the end of the try
block, the statements of the finally block are executed.
o Moreover, if the control leaves a try block as a result of a throw
statement or a jump statement such as break , continue, or goto, the
statements of the finally block are executed.
o The finally block is basically useful in three situations: to avoid
duplication of statements, to release resources after an exception has
been thrown and to assign a value to an object or display a message
that may be useful to the program.
int[] numbers = new int[2];
try
{
numbers[0] = 23;
numbers[1] = 32;
numbers[2] = 42;
foreach(int i in numbers)
Console.WriteLine(i);
}
catch(IndexOutOfRangeException ex)
{
Console.WriteLine("An index was out of range!");
}
catch(Exception ex)
{
Console.WriteLine("Some sort of error occured: " + ex.Message);
}
finally
{
Console.WriteLine("It's the end of our try block.Time to clean up!");
}
Console.ReadLine();
COMMON EXCEPTION CLASSES
COMMON EXCEPTION CLASSES
o Exception Class - - Cause
o SystemException - A failed run-time check;used as a base class for other.
o AccessException - Failure to access a type member, such as a method or field.
o ArgumentException - An argument to a method was invalid.
o ArgumentNullException - A null argument was passed to a method that doesn't accept it.
o ArgumentOutOfRangeException - Argument value is out of range.
o BadImageFormatException - Image is in the wrong format.
o CoreException - Base class for exceptions thrown by the runtime.
o DivideByZeroException - An attempt was made to divide by zero.
o FormatException - The format of an argument is wrong.
o InvalidOperationException - A method was called at an invalid time.
o MissingMemberException - An invalid version of a DLL was accessed.
o NotFiniteNumberException - A number is not valid.
o NotSupportedException - Indicates sthat a method is not implemented by a class.
EXCEPTIONS HAVETHE FOLLOWING
PROPERTIES:
o Exceptions are types that all ultimately derive from System.Exception.
o Use a try block around the statements that might throw exceptions.
o Once an exception occurs in the try block, the flow of control jumps to the
first associated exception handler that is present anywhere in the call stack. In
C#, the catch keyword is used to define an exception handler.
o If no exception handler for a given exception is present, the program stops
executing with an error message.
EXCEPTIONS HAVETHE FOLLOWING
PROPERTIES:
o Do not catch an exception unless you can handle it and leave the application
in a known state. If you catch System.Exception, rethrow it using the throw
keyword at the end of the catch block.
o If a catch block defines an exception variable, you can use it to obtain more
information about the type of exception that occurred.
o Exceptions can be explicitly generated by a program by using the throw
keyword.
o Exception objects contain detailed information about the error, such as the
state of the call stack and a text description of the error.
o Code in a finally block is executed even if an exception is thrown. Use a
finally block to release resources, for example to close any streams or files
that were opened in the try block.
THANKYOU

More Related Content

What's hot

130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
Hemant Chetwani
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
14 exception handling
14 exception handling14 exception handling
14 exception handlingjigeno
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
sharqiyem
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
Victer Paul
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaPrasad Sawant
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 
Exception handling
Exception handlingException handling
Exception handlingRavi Sharda
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 

What's hot (20)

130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
14 exception handling
14 exception handling14 exception handling
14 exception handling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling
Exception handlingException handling
Exception handling
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception
Java exception Java exception
Java exception
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handling Exception handling
Exception handling
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 

Similar to 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
AboMohammad10
 
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
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exceptions
ExceptionsExceptions
Exceptions
motthu18
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
Shipra Swati
 
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
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Exceptions
ExceptionsExceptions
Exceptions
DeepikaT13
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 

Similar to Exceptions overview (20)

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
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
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
 
Exceptions
ExceptionsExceptions
Exceptions
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
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
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions
ExceptionsExceptions
Exceptions
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
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
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 

Recently uploaded

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
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
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
 
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
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
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
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
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
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
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
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
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
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
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
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 

Recently uploaded (20)

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
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
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 -...
 
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...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
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...
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
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
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
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...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
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...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 

Exceptions overview

  • 2. WHAT IS AN EXCEPTION? An exception is an error condition or unexpected behavior encountered by an executing program during runtime. In fact the name exception comes from the fact that although a problem can occur; the problem occurs infrequently. Trapping and handling of runtime errors is one of the most crucial tasks ahead of any programmer.As a developer, you sometimes seem to spend more time checking for errors and handling them than you do on the core logic of the actual program.You can address this issue by using system exceptions that are designed for the purpose of handling errors. In this article, you will learn how to catch and handle exceptions in C#.
  • 3. EXCEPTIONS o The C# language's exception handling features provide a way to deal with any unexpected or exceptional situations that arise while a program is running. o Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards.
  • 4. EXCEPTIONS The .NET base class libraries define numerous exceptions such as o FormatException o IndexOutOfRangeException o FileNotFoundException o ArgumentOutOfRangeException .NET platform provides a standard technique to send and trap runtime errors: structured exception handling (SEH).
  • 5. THE ATOMS OF .NET EXCEPTION HANDLING o Programming with structured exception handling o involves the use of four interrelated entities: o A class type that represents the details of the exception that occurred o A member that throws an instance of the exception class to the caller o A block of code on the caller’s side that invokes the exception-prone member o A block of code on the caller’s side that will process (or catch) the exception should it occur
  • 6. WHAT ARETHE OTHER EXCEPTION CLASSES? Here's a list of few Common Exception Classes: o System.ArithmeticException-A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException o System.ArrayTypeMismatchException-Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array. o System.DivideByZeroException-Thrown when an attempt to divide an integral value by zero occurs. o System.IndexOutOfRangeException-Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.
  • 7. WHAT ARETHE OTHER EXCEPTION CLASSES? o System.InvalidCastExceptionThrown when an explicit conversion from a base type or interface to derived types fails at run time. o System.MulticastNotSupportedException-Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type. o System.NullReferenceException-Thrown when a null reference is used in a way that causes the referenced object to be required. o System.OutOfMemoryException-Thrown when an attempt to allocate memory (via new) fails. o System.OverflowException-Thrown when an arithmetic operation in a checked context overflows.
  • 8. EXCEPTIONS OVERVIEW o When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated. o Once an exception occurs, the flow of control immediately jumps to an associated exception handler, if one is present. o If no exception handler for a given exception is present, the program stops executing with an error message. o Actions that may result in an exception are executed with the try keyword. o An exception handler is a block of code that is executed when an exception occurs. In C#, the catch keyword is used to define an exception handler. o Exceptions can be explicitly generated by a program using the throw keyword. o Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error. o Code in a finally block is executed even if an exception is thrown, thus allowing a program to release resources.
  • 9. class Program { static void Main(string[] args) { int[] numbers = new int[2]; numbers[0] = 23; numbers[1] = 32; numbers[2] = 42; foreach(int i in numbers) Console.WriteLine(i); Console.ReadLine(); } }
  • 10. WHAT IS EXCEPTION HANDLING ANDWHY DOWE NEED IT? o The mark of a good, robust program is planning for the unexpected, and recovering if it does happen. Errors can happen at almost any time during the compilation or execution of a program. o We can detect and deal with these errors using Exception Handling. Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. o At the heart of the .NET Framework is the Common Language Runtime (CLR) which in addition to acting as a virtual machine and interpreting and executing IL code on the fly, performs numerous other functions such as type safety checking, memory management, garbage collection and Exception handling.
  • 11. WHAT IS EXCEPTION HANDLING ANDWHY DOWE NEED IT? o The .NET framework contains lots of standard exceptions. It allows you to define how the system reacts in unexpected situations like 'File not found' , 'Out of Memory' , bad logic, non-availability of operating system resources other than memory, 'Index out of bounds' and so on. o When the code which has a problem, is executed, it 'raises an exception'. If a programmer does not provide a mechanism to handle these anomalies, the .NET run time environment provides a default mechanism, which terminates the program execution.This mechanism is a structured exception handling mechanism.
  • 12. try { // this code may cause an exception. // If it does cause an exception, the execution will not continue. // Instead,it will jump to the 'catch' block. } catch (Exception ex) { // I get executed when an exception occurs in the try block. // Write the error handling code here. }
  • 13. class Program { static void Main(string[] args) { int[] numbers = new int[2]; try { numbers[0] = 23; numbers[1] = 32; numbers[2] = 42; foreach(int i in numbers) Console.WriteLine(i); } catch { Console.WriteLine("Something went wrong!"); } Console.ReadLine(); } }
  • 15. o Exception is the most general type of exception.The rules of exception handling tells us that we should always use the least general type of exception, and in this case, we actually know the exact type of exception generated by our code. How? BecauseVisual Studio told us when we didn't handle it. If you're in doubt, the documentation usually describes which exception(s) a method may throw.Another way of finding out is using the Exception class to tell us - change the output line to this: o Console.WriteLine("An error occured: " + ex.GetType().ToString()); o The result is, as expected, IndexOutOfRangeException.We should therefore handle this exception, but nothing prevents us from handling more than one exception. In some situations you might wish to do different things, depending on which exception was thrown.
  • 16. catch(IndexOutOfRangeException ex) { Console.WriteLine("An index was out of range!"); } catch(Exception ex) { Console.WriteLine("Some sort of error occured: " + ex.Message); }
  • 17. OK, BUT WHAT ABOUTTHE FINALLY BLOCK? o C# provides the finally block to enclose a set of statements that need to be executed regardless of the course of control flow. So as a result of normal execution, if the control flow reaches the end of the try block, the statements of the finally block are executed. o Moreover, if the control leaves a try block as a result of a throw statement or a jump statement such as break , continue, or goto, the statements of the finally block are executed. o The finally block is basically useful in three situations: to avoid duplication of statements, to release resources after an exception has been thrown and to assign a value to an object or display a message that may be useful to the program.
  • 18. int[] numbers = new int[2]; try { numbers[0] = 23; numbers[1] = 32; numbers[2] = 42; foreach(int i in numbers) Console.WriteLine(i); } catch(IndexOutOfRangeException ex) { Console.WriteLine("An index was out of range!"); } catch(Exception ex) { Console.WriteLine("Some sort of error occured: " + ex.Message); } finally { Console.WriteLine("It's the end of our try block.Time to clean up!"); } Console.ReadLine();
  • 20. COMMON EXCEPTION CLASSES o Exception Class - - Cause o SystemException - A failed run-time check;used as a base class for other. o AccessException - Failure to access a type member, such as a method or field. o ArgumentException - An argument to a method was invalid. o ArgumentNullException - A null argument was passed to a method that doesn't accept it. o ArgumentOutOfRangeException - Argument value is out of range. o BadImageFormatException - Image is in the wrong format. o CoreException - Base class for exceptions thrown by the runtime. o DivideByZeroException - An attempt was made to divide by zero. o FormatException - The format of an argument is wrong. o InvalidOperationException - A method was called at an invalid time. o MissingMemberException - An invalid version of a DLL was accessed. o NotFiniteNumberException - A number is not valid. o NotSupportedException - Indicates sthat a method is not implemented by a class.
  • 21. EXCEPTIONS HAVETHE FOLLOWING PROPERTIES: o Exceptions are types that all ultimately derive from System.Exception. o Use a try block around the statements that might throw exceptions. o Once an exception occurs in the try block, the flow of control jumps to the first associated exception handler that is present anywhere in the call stack. In C#, the catch keyword is used to define an exception handler. o If no exception handler for a given exception is present, the program stops executing with an error message.
  • 22. EXCEPTIONS HAVETHE FOLLOWING PROPERTIES: o Do not catch an exception unless you can handle it and leave the application in a known state. If you catch System.Exception, rethrow it using the throw keyword at the end of the catch block. o If a catch block defines an exception variable, you can use it to obtain more information about the type of exception that occurred. o Exceptions can be explicitly generated by a program by using the throw keyword. o Exception objects contain detailed information about the error, such as the state of the call stack and a text description of the error. o Code in a finally block is executed even if an exception is thrown. Use a finally block to release resources, for example to close any streams or files that were opened in the try block.