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

Mais conteúdo relacionado

Mais procurados

14 exception handling
14 exception handling14 exception handling
14 exception handling
jigeno
 
Exception Handling
Exception HandlingException Handling
Exception Handling
backdoor
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Prasad Sawant
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
aptechsravan
 
Exception handling
Exception handlingException handling
Exception handling
Ravi Sharda
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 

Mais procurados (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
 

Semelhante a 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
 
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
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
exceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.pptexceptionvdffhhhccvvvv-handling-in-java.ppt
exceptionvdffhhhccvvvv-handling-in-java.ppt
yjrtytyuu
 

Semelhante a 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
 
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
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 

Último

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 

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.