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

PPTX
Exception Handling in Java
PPSX
Exception Handling
PPT
Exception handling in java
PPTX
Exception handling in java
PPTX
Exception handling
PPTX
Java exception handling
PPT
Exception handling
PDF
Best Practices in Exception Handling
Exception Handling in Java
Exception Handling
Exception handling in java
Exception handling in java
Exception handling
Java exception handling
Exception handling
Best Practices in Exception Handling

What's hot (20)

PPTX
130410107010 exception handling
PPT
12 exception handling
PPT
Exception handling
PDF
14 exception handling
ODP
Exception Handling In Java
PPT
Exception Handling Java
PPTX
Exception handling
PPT
C# Exceptions Handling
PPT
Java: Exception
PPTX
Exception handling
PPT
Java exception
PPT
Exception Handling
PPT
Exception handling
PDF
Java - Exception Handling Concepts
PPTX
Exception handling in Java
PPT
exception handling in java
PDF
Exception handling
PDF
Exception handling
PPT
Exception handling
PPTX
Exceptions in Java
130410107010 exception handling
12 exception handling
Exception handling
14 exception handling
Exception Handling In Java
Exception Handling Java
Exception handling
C# Exceptions Handling
Java: Exception
Exception handling
Java exception
Exception Handling
Exception handling
Java - Exception Handling Concepts
Exception handling in Java
exception handling in java
Exception handling
Exception handling
Exception handling
Exceptions in Java
Ad

Similar to Exceptions overview (20)

PPT
Exception Handling Exception Handling Exception Handling
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PDF
Ch-1_5.pdf this is java tutorials for all
PPT
Exceptions
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPT
Java Exception Handling & IO-Unit-3 (1).ppt
PPTX
Interface andexceptions
PPTX
Exception Handling.pptx
PDF
Class notes(week 8) on exception handling
PPTX
UNIT 2.pptx
PDF
Java unit 11
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Java -Exception handlingunit-iv
PPTX
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
PPT
Exception handling
PPT
Exceptions
PPT
Md07 exceptions&assertion
PPTX
UNIT-3.pptx Exception Handling and Multithreading
PPTX
Exception handling in java
Exception Handling Exception Handling Exception Handling
unit 4 msbte syallbus for sem 4 2024-2025
Ch-1_5.pdf this is java tutorials for all
Exceptions
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
Interface andexceptions
Exception Handling.pptx
Class notes(week 8) on exception handling
UNIT 2.pptx
Java unit 11
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
Java -Exception handlingunit-iv
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Exception handling
Exceptions
Md07 exceptions&assertion
UNIT-3.pptx Exception Handling and Multithreading
Exception handling in java
Ad

Recently uploaded (20)

PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PPTX
Spectroscopy.pptx food analysis technology
PDF
KodekX | Application Modernization Development
PDF
Approach and Philosophy of On baking technology
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
cuic standard and advanced reporting.pdf
PPTX
MYSQL Presentation for SQL database connectivity
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Electronic commerce courselecture one. Pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
Building Integrated photovoltaic BIPV_UPV.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Unlocking AI with Model Context Protocol (MCP)
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
“AI and Expert System Decision Support & Business Intelligence Systems”
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Spectroscopy.pptx food analysis technology
KodekX | Application Modernization Development
Approach and Philosophy of On baking technology
Spectral efficient network and resource selection model in 5G networks
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Review of recent advances in non-invasive hemoglobin estimation
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
cuic standard and advanced reporting.pdf
MYSQL Presentation for SQL database connectivity
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Encapsulation_ Review paper, used for researhc scholars
Electronic commerce courselecture one. Pdf
MIND Revenue Release Quarter 2 2025 Press Release

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.