SlideShare a Scribd company logo
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.");
}
Exception
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.

•
•
•
•
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 …..

More Related Content

What's hot (20)

PPTX
Exceptions in Java
Vadym Lotar
 
PPTX
Chap2 exception handling
raksharao
 
PPT
Java: Exception
Tareq Hasan
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPT
Exception Handling Java
ankitgarg_er
 
PPTX
Exceptionhandling
Nuha Noor
 
ODP
Exception Handling In Java
parag
 
PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PPTX
Exception handling
Abhishek Pachisia
 
PPTX
Exception handling in java
yugandhar vadlamudi
 
ODP
Exception handling in java
priyankazope
 
PPTX
7.error management and exception handling
Deepak Sharma
 
PPTX
Java Exceptions and Exception Handling
MaqdamYasir
 
PPTX
What is Exception Handling?
Syed Bahadur Shah
 
PPT
Exception handling
M Vishnuvardhan Reddy
 
PDF
javaexceptions
Arjun Shanka
 
PDF
Exception Handling
Alpesh Oza
 
PPTX
43c
Sireesh K
 
PPT
Exception handling in java
Pratik Soares
 
PPT
Exception handling
Tata Consultancy Services
 
Exceptions in Java
Vadym Lotar
 
Chap2 exception handling
raksharao
 
Java: Exception
Tareq Hasan
 
Java exception handling
BHUVIJAYAVELU
 
Exception Handling Java
ankitgarg_er
 
Exceptionhandling
Nuha Noor
 
Exception Handling In Java
parag
 
Exception Handling in Java
lalithambiga kamaraj
 
Exception handling
Abhishek Pachisia
 
Exception handling in java
yugandhar vadlamudi
 
Exception handling in java
priyankazope
 
7.error management and exception handling
Deepak Sharma
 
Java Exceptions and Exception Handling
MaqdamYasir
 
What is Exception Handling?
Syed Bahadur Shah
 
Exception handling
M Vishnuvardhan Reddy
 
javaexceptions
Arjun Shanka
 
Exception Handling
Alpesh Oza
 
Exception handling in java
Pratik Soares
 
Exception handling
Tata Consultancy Services
 

Similar to Exception (20)

PPTX
Exception handling in .net
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Exception Handling in C#
Abid Kohistani
 
PPTX
Exceptions overview
Bharath K
 
PPTX
12. Exception Handling
Intro C# Book
 
PPT
Exceptions
motthu18
 
PPTX
C Sharp Tutorial : C Sharp Exception
Courseing Online
 
PPTX
IakakkakjabbhjajjjjjajjajwsjException.pptx
KingDietherManay1
 
PPT
Exceptions
DeepikaT13
 
PPTX
Exception Handlin g C#.pptx
R S Anu Prabha
 
PPTX
3.C#
Raghu nath
 
PPT
12 Exceptions handling
maznabili
 
PPT
C# Exceptions Handling
sharqiyem
 
PPTX
6-Error Handling.pptx
amiralicomsats3
 
PPTX
Java SE 11 Exception Handling
Ashwin Shiv
 
PPTX
41c
Sireesh K
 
PPTX
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
ZachariahAbera
 
PPTX
Unit2_2.pptx Chapter 2 Introduction to C#
Priyanka Jadhav
 
PPTX
Role of .NET in Exception Handling
Asrarulhaq Maktedar
 
PPTX
Exception handling in c
Memo Yekem
 
PPTX
Exception handling in c
Memo Yekem
 
Exception Handling in C#
Abid Kohistani
 
Exceptions overview
Bharath K
 
12. Exception Handling
Intro C# Book
 
Exceptions
motthu18
 
C Sharp Tutorial : C Sharp Exception
Courseing Online
 
IakakkakjabbhjajjjjjajjajwsjException.pptx
KingDietherManay1
 
Exceptions
DeepikaT13
 
Exception Handlin g C#.pptx
R S Anu Prabha
 
12 Exceptions handling
maznabili
 
C# Exceptions Handling
sharqiyem
 
6-Error Handling.pptx
amiralicomsats3
 
Java SE 11 Exception Handling
Ashwin Shiv
 
Chapter_4_WP_with_C#_Exception_Handling_student_1.0.pptx
ZachariahAbera
 
Unit2_2.pptx Chapter 2 Introduction to C#
Priyanka Jadhav
 
Role of .NET in Exception Handling
Asrarulhaq Maktedar
 
Exception handling in c
Memo Yekem
 
Exception handling in c
Memo Yekem
 
Ad

More from abhay singh (15)

PPT
Iso 27001
abhay singh
 
PPT
Web service
abhay singh
 
PPT
Unsafe
abhay singh
 
PPTX
Threading
abhay singh
 
PPT
Preprocessor
abhay singh
 
PPT
Networking and socket
abhay singh
 
PPT
Namespace
abhay singh
 
PPT
Inheritance
abhay singh
 
PPT
Generic
abhay singh
 
PPT
Gdi
abhay singh
 
PPT
Delegate
abhay singh
 
PPT
Constructor
abhay singh
 
PPT
Collection
abhay singh
 
PPT
Ado
abhay singh
 
PPT
Operator overloading
abhay singh
 
Iso 27001
abhay singh
 
Web service
abhay singh
 
Unsafe
abhay singh
 
Threading
abhay singh
 
Preprocessor
abhay singh
 
Networking and socket
abhay singh
 
Namespace
abhay singh
 
Inheritance
abhay singh
 
Generic
abhay singh
 
Delegate
abhay singh
 
Constructor
abhay singh
 
Collection
abhay singh
 
Operator overloading
abhay singh
 
Ad

Recently uploaded (20)

PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PDF
John Keats introduction and list of his important works
vatsalacpr
 
PPTX
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
PDF
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
PDF
Tips for Writing the Research Title with Examples
Thelma Villaflores
 
PDF
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
PPTX
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
PPTX
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PPTX
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
PPTX
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
PPTX
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
John Keats introduction and list of his important works
vatsalacpr
 
Continental Accounting in Odoo 18 - Odoo Slides
Celine George
 
My Thoughts On Q&A- A Novel By Vikas Swarup
Niharika
 
Tips for Writing the Research Title with Examples
Thelma Villaflores
 
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
LDP-2 UNIT 4 Presentation for practical.pptx
abhaypanchal2525
 
Applied-Statistics-1.pptx hardiba zalaaa
hardizala899
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Gupta Art & Architecture Temple and Sculptures.pptx
Virag Sontakke
 
Applications of matrices In Real Life_20250724_091307_0000.pptx
gehlotkrish03
 
HEALTH CARE DELIVERY SYSTEM - UNIT 2 - GNM 3RD YEAR.pptx
Priyanshu Anand
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 

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!"); } } }
  • 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. • • • •
  • 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 …..