SlideShare une entreprise Scribd logo
1  sur  22
Exception Handling
• An exception is an error that occurs at
runtime.
• Exception handling streamlines errorhandling by allowing your program to define
a block of code, called an exception
handler, that is executed automatically
when an error occurs.
• It is not necessary to manually check the
success or failure of each specific operation
or method call.
System.Exception Class
• In C#, exceptions are represented by
classes.
• All exception classes must be derived
from the built-in exception class
Exception, which is part of the System
namespace.
• Thus, all exceptions are subclasses of
Exception.
• One very important subclass of Exception
is SystemException.
• SystemException simply defines the top
of the standard exceptions hierarchy.
• The .NET Framework defines several
built-in exceptions that are derived from
SystemException.
• For example, when a division-by-zero is
attempted, a DivideByZeroException
exception is generated.
Fundamentals
• C# exception handling is managed via
four keywords: try, catch, throw , and
finally.
• program statements that you want to
monitor for exceptions are contained
within a try block. If an exception occurs
within the try block, it is thrown. Your
code can catch this exception using catch
and handle it in some rational manner.
Example
class ExcDemo1
{
static void Main()
{
int[] nums = new int[4];
try {
Console.WriteLine("Before exception is
generated.");
for (int i = 0; i < 10; i++)
{
nums[i] = i;
Console.WriteLine("nums[{0}]: {1}", i, nums[i]);
}
}
//specifying exOb is optional.

catch (IndexOutOfRangeException exOb)
{
Console.WriteLine("Index out-of-bounds! “);
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
} Console.WriteLine("After catch block.");
} }
Catching All Exceptions
• you might want to catch all exceptions, no
matter the type. To do this, use a catch
clause that specifies no exception type or
variable. It has this general form:
catch {
// handle exceptions
}
• This creates a “catch all” handler that
ensures that all exceptions are caught by
your program.
class ExcDemo5 {
static void Main() {
int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 };
int[] denom = { 2, 0, 4, 4, 0, 8 };
for(int i=0; i < numer.Length; i++) {
try {
Console.WriteLine(numer[i] + " / " + denom[i]
+ " is " + numer[i]/denom[i]);
}
catch {
Console.WriteLine("Some except
occurred.");} }
}
• There is one point to remember about
using a catch-all catch: It must be the
last catch clause in the catch sequence.
Nesting try Blocks
try { // outer try
for(int i=0; i < numer.Length; i++) {
try { // nested try
Console.WriteLine(numer[i] + " / " +
denom[i] + " is " +
numer[i]/denom[i]);
}
catch (DivideByZeroException) {
Console.WriteLine("Can't divide by Zero!");
}
} }
catch (IndexOutOfRangeException) {
Console.WriteLine("No matching
element found.");
}
Throwing an Exception
• System-generated exceptions are
automatically thrown by the runtime
system.
• To manually throw an exception, use the
keyword throw .
• Its general form is shown here:
throw exceptOb ;
• The exceptOb must be an object of an
exception class derived from Exception.
class ThrowDemo {
static void Main() {
try {
Console.WriteLine("Before throw.");
throw new DivideByZeroException();
}
catch (DivideByZeroException) {
Console.WriteLine("Exception caught.");
}
Console.WriteLine("After try/catch
statement."); }}
Using finally
• that method may have opened a file or a
network connection that needs to be
closed. Such types of circumstances are
common in programming,
• and C# provides a convenient way to
handle them: finally.
finally{
//finally code
}
Exception Properties
•

Exception defines several properties. The most interesting are
Message, StackTrace, Source, HelpLink and TargetSite. All are
read-only.

•
•

Message contains a string that describes the nature of the error.
StackTrace contains a string that contains the stack of calls that
lead to the exception.
TargetSite obtains an object that specifies the method that
generated the exception.
The HelpLink here is empty because it was not defined on the
exception.
the Source is the application name.
InnerException-Gets the Exception instance that caused the
current exception.

•
•
•
•
• Error is human made mistake. Error - When the
software deviates from a correct value called error.
• Bug: Error which appears during testing phase.
• Bugs arise from mistakes and errors, made by people,
in either a program’s source code or its design.” Bug When the software does not perform as expected.
• Exception handling is an in built mechanism in .NET
framework to detect and handle run time errors. 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. C# exception handling
is managed via four keywords: try, catch, throw, and
finally.
Race Condition
• A Race Condition occurs when two (or more) threads
attempt to access a shared resource at the same time,
without proper synchronization.
• For example, one thread may be writing a new value to a
variable while another thread is incrementing the
variable’s current value. Without synchronization, the
new value of the variable will depend on the order in
which he threads execute. In situations like this, the two
threads are said to be “racing each other,” with the final
outcome determined by which thread finishes first.
• The solution is prevention: careful programming that
properly synchronizes access to shared resources.
Deadlock
• When developing multithreaded programs, you must be
careful to avoid deadlock and race conditions.
• Deadlock is, as the name implies, a situation in which
one thread is waiting for another thread to do something,
but that other thread is waiting on the first. Thus, both
threads are suspended, waiting for each other, and
neither executes.
• This situation is analogous to two overly polite people
both insisting that the other step through a door first!
• To avoid deadlock, careful programming and thorough
testing is required. In general, if a multithreaded program
occasionally “hangs,” deadlock is the likely cause.
InvalidCastException Class
Mscorlib.dll
• A runtime cast is invalid.
• The exception that is thrown for invalid casting
or explicit conversion.
• An InvalidCastException is generated by the
runtime when a statement tries to cast one
reference type to a reference type that is not
compatible.
• Casts that use the type name in ( ) parentheses
are called explicit casts.
InvalidCastException Class
using System.IO;
using System.Text;
class Program
{
static void Main()
{
StringBuilder reference1 = new StringBuilder();
object reference2 = reference1;
StreamReader reference3 = (StreamReader)reference2;

}
}

output
Unhandled Exception: System.InvalidCastException: Unable to
cast object of type 'System.Text.StringBuilder' to type
'System.IO.StreamReader'. at Program.Main() in …..

Contenu connexe

Tendances

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception HandlingMaqdamYasir
 
Exception Handling
Exception HandlingException Handling
Exception HandlingAlpesh Oza
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 

Tendances (20)

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Exception handling
Exception handling Exception handling
Exception handling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
43c
43c43c
43c
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 

Similaire à Exception

Similaire à Exception (20)

Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
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
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
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
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
JAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - MultithreadingJAVA PROGRAMMING- Exception handling - Multithreading
JAVA PROGRAMMING- Exception handling - Multithreading
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 
Exception
ExceptionException
Exception
 

Plus de abhay singh (15)

Iso 27001
Iso 27001Iso 27001
Iso 27001
 
Web service
Web serviceWeb service
Web service
 
Unsafe
UnsafeUnsafe
Unsafe
 
Threading
ThreadingThreading
Threading
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Networking and socket
Networking and socketNetworking and socket
Networking and socket
 
Namespace
NamespaceNamespace
Namespace
 
Inheritance
InheritanceInheritance
Inheritance
 
Generic
GenericGeneric
Generic
 
Gdi
GdiGdi
Gdi
 
Delegate
DelegateDelegate
Delegate
 
Constructor
ConstructorConstructor
Constructor
 
Collection
CollectionCollection
Collection
 
Ado
AdoAdo
Ado
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 

Dernier

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 

Dernier (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 

Exception

  • 1. Exception Handling • An exception is an error that occurs at runtime. • Exception handling streamlines errorhandling by allowing your program to define a block of code, called an exception handler, that is executed automatically when an error occurs. • It is not necessary to manually check the success or failure of each specific operation or method call.
  • 2. System.Exception Class • In C#, exceptions are represented by classes. • All exception classes must be derived from the built-in exception class Exception, which is part of the System namespace. • Thus, all exceptions are subclasses of Exception. • One very important subclass of Exception is SystemException.
  • 3. • SystemException simply defines the top of the standard exceptions hierarchy. • The .NET Framework defines several built-in exceptions that are derived from SystemException. • For example, when a division-by-zero is attempted, a DivideByZeroException exception is generated.
  • 4. Fundamentals • C# exception handling is managed via four keywords: try, catch, throw , and finally. • program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception using catch and handle it in some rational manner.
  • 5. Example class ExcDemo1 { static void Main() { int[] nums = new int[4]; try { Console.WriteLine("Before exception is generated."); for (int i = 0; i < 10; i++) { nums[i] = i;
  • 6. Console.WriteLine("nums[{0}]: {1}", i, nums[i]); } } //specifying exOb is optional. catch (IndexOutOfRangeException exOb) { Console.WriteLine("Index out-of-bounds! “); } catch (DivideByZeroException) { Console.WriteLine("Can't divide by Zero!"); } Console.WriteLine("After catch block."); } }
  • 7. Catching All Exceptions • you might want to catch all exceptions, no matter the type. To do this, use a catch clause that specifies no exception type or variable. It has this general form: catch { // handle exceptions } • This creates a “catch all” handler that ensures that all exceptions are caught by your program.
  • 8. class ExcDemo5 { static void Main() { int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; int[] denom = { 2, 0, 4, 4, 0, 8 }; for(int i=0; i < numer.Length; i++) { try { Console.WriteLine(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); }
  • 9. catch { Console.WriteLine("Some except occurred.");} } } • There is one point to remember about using a catch-all catch: It must be the last catch clause in the catch sequence.
  • 10. Nesting try Blocks try { // outer try for(int i=0; i < numer.Length; i++) { try { // nested try Console.WriteLine(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); } catch (DivideByZeroException) { Console.WriteLine("Can't divide by Zero!"); } } }
  • 12.
  • 13. Throwing an Exception • System-generated exceptions are automatically thrown by the runtime system. • To manually throw an exception, use the keyword throw . • Its general form is shown here: throw exceptOb ; • The exceptOb must be an object of an exception class derived from Exception.
  • 14. class ThrowDemo { static void Main() { try { Console.WriteLine("Before throw."); throw new DivideByZeroException(); } catch (DivideByZeroException) { Console.WriteLine("Exception caught."); } Console.WriteLine("After try/catch statement."); }}
  • 15. Using finally • that method may have opened a file or a network connection that needs to be closed. Such types of circumstances are common in programming, • and C# provides a convenient way to handle them: finally. finally{ //finally code }
  • 16. Exception Properties • Exception defines several properties. The most interesting are Message, StackTrace, Source, HelpLink and TargetSite. All are read-only. • • Message contains a string that describes the nature of the error. StackTrace contains a string that contains the stack of calls that lead to the exception. TargetSite obtains an object that specifies the method that generated the exception. The HelpLink here is empty because it was not defined on the exception. the Source is the application name. InnerException-Gets the Exception instance that caused the current exception. • • • •
  • 17.
  • 18. • Error is human made mistake. Error - When the software deviates from a correct value called error. • Bug: Error which appears during testing phase. • Bugs arise from mistakes and errors, made by people, in either a program’s source code or its design.” Bug When the software does not perform as expected. • Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. 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. C# exception handling is managed via four keywords: try, catch, throw, and finally.
  • 19. Race Condition • A Race Condition occurs when two (or more) threads attempt to access a shared resource at the same time, without proper synchronization. • For example, one thread may be writing a new value to a variable while another thread is incrementing the variable’s current value. Without synchronization, the new value of the variable will depend on the order in which he threads execute. In situations like this, the two threads are said to be “racing each other,” with the final outcome determined by which thread finishes first. • The solution is prevention: careful programming that properly synchronizes access to shared resources.
  • 20. Deadlock • When developing multithreaded programs, you must be careful to avoid deadlock and race conditions. • Deadlock is, as the name implies, a situation in which one thread is waiting for another thread to do something, but that other thread is waiting on the first. Thus, both threads are suspended, waiting for each other, and neither executes. • This situation is analogous to two overly polite people both insisting that the other step through a door first! • To avoid deadlock, careful programming and thorough testing is required. In general, if a multithreaded program occasionally “hangs,” deadlock is the likely cause.
  • 21. InvalidCastException Class Mscorlib.dll • A runtime cast is invalid. • The exception that is thrown for invalid casting or explicit conversion. • An InvalidCastException is generated by the runtime when a statement tries to cast one reference type to a reference type that is not compatible. • Casts that use the type name in ( ) parentheses are called explicit casts.
  • 22. InvalidCastException Class using System.IO; using System.Text; class Program { static void Main() { StringBuilder reference1 = new StringBuilder(); object reference2 = reference1; StreamReader reference3 = (StreamReader)reference2; } } output Unhandled Exception: System.InvalidCastException: Unable to cast object of type 'System.Text.StringBuilder' to type 'System.IO.StreamReader'. at Program.Main() in …..