Top Banner
Exception Handling • An exception is an error that occurs at runtime. • Exception handling streamlines error- handling 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.
22
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Exception

Exception Handling• An exception is an error that occurs at

runtime.

• Exception handling streamlines error- handling 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.

Page 2: Exception

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.

Page 3: Exception

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

Page 4: Exception

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.

Page 5: Exception

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;

Example

Page 6: Exception

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.");

} }

Page 7: Exception

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.

Page 8: Exception

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]);

}

Page 9: Exception

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.

Page 10: Exception

Nesting try Blockstry { // 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!");

} } }

Page 11: Exception

catch (IndexOutOfRangeException) {

Console.WriteLine("No matching element found.");

}

Page 12: Exception
Page 13: 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.

Page 14: 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."); }}

Page 15: Exception

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

}

Page 16: Exception

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.

Page 17: Exception
Page 18: 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.

Page 19: Exception

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.

Page 20: Exception

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.

Page 21: Exception

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. 

Page 22: Exception

InvalidCastException Classusing System.IO;using System.Text;class Program{ static void Main() {

StringBuilder reference1 = new StringBuilder();object reference2 = reference1;

StreamReader reference3 = (StreamReader)reference2; }}

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