Application pool and App-domain , both of them can provide isolation's, but use different approaches. Application pool use the process to isolate the applications which works without .NET. But App-domain is another isolation methods provided by .NET. If your server host thousands of web sites, you wont use thousands of the application pool to isolate the web sites, just because, too many processes running will kill the OS. However, sometime you need application pool. One of the advantages for application pool is that you can config the identity for application pool. Also you have more flexible options to recycle the application pool. At least right now, IIS didn't provide explicit options to recycle the app-domain.
If you only have a single site in your app pool, then an app pool and an App-domain recycle will be quite similar. The app pool recycle will recycle the entire w3wp.exe process while the App-domain will recycle the .NET App-domain only, but since most of what that needs to be recycled lives in the App-domain, they will achieve the same thing. It's just a matter of which is easier for you to do. But, if the App-domain recycle doesn't do the trick, then try a full app pool recycle. This will depend on your situation.
If you have multiple sites in the app pool, then an App-domain is preferred because it won't touch any of the other sites or applications in the app pool and is isolated to just the single application/App-domain in the app pool.
Please see my answer below for the differences between appdomain and application pool...
1. Basically, an application is an IIS term, which will create a sandbox, or a set of boundaries in order to separate different sites, or parts of sites, from the others. 2. AppDomain is a .NET term, which contains InProc session state so that if an AppDomain is killed or recycled, all of your session state information will be lost. 3. Applications can have multiple AppDomains in them, although most of the time there is a one-to-one relationship between them. 4. In IIS6 and greater, there is the option of creating groups or "pools" of applications that can be bundled together or separated, however, it will decide by server administer. These are called Application Pools. Each application pool runs under its own w3wp.exe worker process. 5. In IIS, it is easy to see an application. A new website is a separate application and any sub-folder can be marked as an application. When they are, the icon beside the folder turns into a picture of some gears. By right-clicking on the folder, you have the option of marking a folder as an application or removing it as an application, if it already is one. Also, in IIS6, in the Application Pools section, you can see all of the applications and which application pool they live under. 6. On the other hand, ASP.NET does not give much visibility into AppDomains, at least not from any visual tools. This is done behind the scenes. Programmatically, you can create them, tear them down or see a list of all running AppDomains. 7. You can recycle an application from IIS. In IIS5, you cannot do it directly unless you recycle the entire web server, but in IIS6 and greater, you can recycle the application pool that the application lives under. It will gracefully die off and a new application will start up to replace it. Or, to word it another way, another w3wp.exe worker process will be started and then the old one will die off after it completes any currently running page requests. 8. You can recycle an AppDomain in ASP.NET through the "touch trick". There are some ways to do it, but the most straightforward is to edit your web.config file in notepad and add a space to an insignificant place. Then save the file. This will cause the AppDomain to recycle. This does not touch the IIS application though. 9. Recycling an AppDomain will come pretty close to starting ASP.NET freshly again for that particular ASP.NET application, so although it does not recycle the application pool, it can give ASP.NET a fresh start in many situations.
******************
This question normally arises when configuring web applications.
To summarize, an AppPool consists of one or more processes. Each web application that you are running consists of (usually, IIRC) one application domain. The issue is when you assign multiple web applications to the same AppPool, while they are separated by the application domain boundary they are still in the same process. This can be less reliable/secure than using a separate AppPool for each web application. On the other hand, it can improve performance by reducing the overhead of multiple processes.
ASP.NET has its own forums. I'd recommend you ask there if you have additional questions about how to set up ASP.NET: http://forums.asp.net/
An Internet Information Services (IIS) application pool is a grouping of URLs that is routed to one or more worker processes. Because application pools define a set of Web applications that share one or more worker processes, they provide a convenient way to administer a set of Web sites and applications and their corresponding worker processes. Process boundaries separate each worker process; therefore, a Web site or application in one application pool will not be affected by application problems in other application pools. Application pools significantly increase both the reliability and manageability of a Web infrastructure.
A boundary that the common language runtime establishes around objects created within the same application scope (that is, anywhere along the sequence of object activations beginning with the application entry point). Application domains help isolate objects created in one application from those created in other applications so that run-time behavior is predictable. Multiple application domains can exist in a single process.
[/quote]
IIS _Application Pool_more than one W3Wp is called web farm.png
An application pool is a container to execute one or more applications/virtual directories, which means for a single application pool, one or more than one websites can be mapped. In a application pool, more than one worker processor can exists. if each website in application pool is mapped to individual worker process, and if any issues occurs in one worker process, only that worker process will
stored and restart, the other process will still run.
Application domain is mapped to individual worker process, that is w3wp.exe. but, there can be more than one application domain mapped to a single worker process.
Application vs. AppDomain
A question was asked on a forum that I frequent which I thought was worth writting a blog about.
Q: What is the difference between an application and an Appdomain? I understand from my research so far that an Appdomain is a container within which ASPX runs and that Apppool is a process that starts the w3wp.exe worker process within which ASP applications run.
A: That’s a good question. Here are some key differences:
An application is an IIS term, but it’s one that ASP.NET utilizes. Essentially it creates a sandbox, or a set of boundaries to separate different sites, or parts of sites, from the others.
An AppDomain is a .NET term. (In IIS7, AppDomains play a larger role within IIS, but for the most part it’s anASP.NET term)
An AppDomain contains InProc session state (the default session state mode). So if an AppDomain is killed/recycled, all of your session state information will be lost. (if you are using the default InProc session state)
Applications can have multiple AppDomains in them although often times there is a one-to-one relationship between them.
In IIS6 and greater, there is the option of creating groups, or “pools” of applications that can be bundled together or separated; however the server administer decides. These are called Application Pools. Each app pool runs under its own w3wp.exe worker process.
In IIS, it’s easy to see an application. A new website is a separate application and any subfolder can be marked as an application. When they are, the icon beside the folder turnes into a picture of some gears. By right-clicking on the folder, you have the option of marking a folder as an application or removing it as an application, if it already is one. Also, in IIS6, in the Application Pools section, you can see all of the applications and which app pool they live under.
ASP.NET, on the other hand, doesn’t give much visibility into AppDomains, at least not from any visual tools. This is done behind the scenes. Programmatically you can create them, tear them down or see a list of all running AppDomains.
You can recycle an application from IIS. In IIS5, you can’t do it directly unless you recycle the entire web server, but in IIS6 and greater, you can recycle the application pool that the application lives under. It will gracefully die off and a new application will start up to replace it. Or, to word it another way, another w3wp.exe worker process will be started and then the old one will die off after it completes any currently running page requests.
You can recycle an AppDomain in ASP.NET through the ‘touch trick’. There are a few ways to do it, but the most straight forward is to edit your web.config file in notepad and add a space to an insignificant place. Then save the file. This will cause the AppDomain to recycle. This *does not* touch the IIS application though.
Recycling an AppDomain will come pretty close to starting ASP.NET fresh again for that particular ASP.NETapplication, so although it doesn’t recycle the apppool, it can give ASP.NET a fresh start in many situations.
dit: After seeing some of the responses to the main response, my suggestion continues with
Add more Try/Catch Blocks to the code.
Put in more check for null variables and lists
Put in more error handling. Do a divide and conquer strategy for this situation. Determine where the errors reside and start putting in error handling, logging and general plumbing to facilitate better code.
If you need to debug a Web application that is running on a production server, this should be done with caution. If you attach to the ASP.NET worker process for debugging and hit a breakpoint, for example, all managed code in the worker process halts. Halting all managed code in the worker process can cause a work stoppage for all users on the server. Before you debug on a production server, consider the potential impact on production work.
Many ASP.NET Web applications reference DLLs that contain business logic or other useful code. Such a reference automatically copies the DLL from your local computer to the \bin folder of the Web application's virtual directory. When you are debugging, remember that your Web application is referencing that copy of the DLL and not the copy on your local computer.
The process for attaching to the ASP.NET worker process is the same as attaching to any other remote process. When you are attached, if you do not have the correct project open, a dialog box appears when the application breaks. This dialog box asks for the location of the source files for the application. The file name that you specify in the dialog box must match the file name specified in the debug symbols on the Web server. For more information, see Attach to Running Processes with the Visual Studio Debugger.
Tracing in asp.net - Part 79
Tracing enables us to view diagnostic information about a request and is very useful when debugging application problems.
Tracing can be turned on or off 1. At the application level or 2. At the page level
To enable tracing at the application level set "trace" element's "enabled"attribute to "true" in web.config. This enables tracing for all pages in the application. <trace enabled="true"/>
To disable tracing for specific pages, set Trace="false" in the webform's "Page" directive <%@Page Language="C#"Trace="false"AutoEventWireup="true"CodeBehind="WebForm1.aspx.cs"Inherits="WebApplication1.WebForm1"%>
An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw.
try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.
catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw: A program throws an exception when a problem shows up. This is done using a throw keyword.
Syntax
Assuming a block will raise and exception, a method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one exception in different situations.
Exception Classes in C# C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:
Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type.
System.NullReferenceException Handles errors generated from deferencing a null object.
System.DivideByZeroException Handles errors generated from dividing a dividend with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException Handles errors generated from insufficient free memory.
System.StackOverflowException Handles errors generated from stack overflow.
Handling Exceptions
C# provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements.
These error handling blocks are implemented using the try, catch and finally keywords. Following is an example of throwing an exception when dividing by zero condition occurs:
using System;
namespace ErrorHandlingApplication
{
class DivNumbers
{
int result;
DivNumbers()
{
result = 0;
}
public void division(int num1, int num2)
{
try
{
result = num1 / num2;
}
catch (DivideByZeroException e)
{
Console.WriteLine("Exception caught: {0}", e);
}
finally
{
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args)
{
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0 Creating User-Defined Exceptions
You can also define your own exception. User-defined exception classes are derived from the ApplicationException class. The following example demonstrates this:
using System; namespace UserDefinedException { class TestTemperature { static void Main(string[] args) { Temperature temp = new Temperature(); try { temp.showTemp(); } catch(TempIsZeroException e) { Console.WriteLine("TempIsZeroException: {0}", e.Message); } Console.ReadKey(); } } } public class TempIsZeroException: ApplicationException { public TempIsZeroException(string message): base(message) { } } public class Temperature { int temperature = 0; public void showTemp() { if(temperature == 0) { throw (new TempIsZeroException("Zero Temperature found")); } else { Console.WriteLine("Temperature: {0}", temperature); } } }
When the above code is compiled and executed, it produces the following result:
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw statement in the catch block to throw the present object as:
Initializes
a new instance of theExceptionclass
with a specified error message and a reference to the inner exception that is
the cause of this exception.
When
a causal relationship exists between two or more exceptions, theInnerExceptionproperty maintains this information.
The outer exception is thrown in response to this inner exception. The code
that handles the outer exception can use the information from the earlier inner
exception to handle the error more appropriately. Supplementary information
about the exception can be stored as a collection of key/value pairs in theDataproperty.
AnExceptionis an object delivered by theExceptionclass. ThisExceptionclass is exposed by theSystem.Exceptionnamespace.Exceptions are used to avoid system failure in an unexpected manner.Exceptionhandles the failure situation that may arise. All theexceptions in the .NET Framework are derived from theSystem.Exceptionclass.
To understandexception, we need to know two basic things:
Somebody sees a failure situation that happened and throws an exception by packing the valid information.
Somebody who knows that a failure may happen catches the exception thrown. We call itExceptionHandler.
Below is a simple example, which shows what happens when anExceptionis not handled:
class ExceptionsEx
{
//001: Start the Program Execution.
publicvoid StartProgram()
{
Console.WriteLine("Making Call to F1() " );
F1();
Console.WriteLine("Successfully returned from F1() " );
}
//002: Set of Function that calls each other
publicvoid F1()
{
Console.WriteLine("Making Call to F2() " );
thrownew System.Exception();
F2();
Console.WriteLine("Successfully returned from F2() " );
}
publicvoid F2()
{
Console.WriteLine("Inside F2 " );
}
//Client 001: Program Entry
[STAThread]
staticvoid Main(string[] args)
{
//Create the Object and start the Execution
ExceptionsEx app = new ExceptionsEx();
app.StartProgram();
}
}
In the above code, look at the function F1 that throws anException. But, there is no handler to deal with the thrownexception. This situation is called an Un-Handledexceptionsituation. When you execute the code, you get an unhandledexceptiondialog.
The above dialog is shown in debug mode, so you may get a chance to break the execution to see where the exception is thrown (or) continue ignoring theexception(not advisable).
In release mode, you will get un-handledExceptionin the form of Application crash.
So, how do we avoid Un-HandledException? Simple, handle it.
2. Handling Exception
To handle the exception, we need to place the code within thetryblock. When an exception occurs inside thetryblock, the control looks for thecatchblock and raises an exception that is handled in thecatchblock. Below is the simple skeleton for thetryandcatchblock:
try
{
//Some Code that may expected to raise an exception
}
catch
{
//Raised exception Handled here
}
The above skeleton handles anyexception. But, the main disadvantage is that we don’t know whatexceptionis raised and who raised theexception. Below is the example that handles theExceptionraised by the function F1 and avoids the crash:
class ExceptionsEx
{
//001: Start the Program Execution.
publicvoid StartProgram()
{
Console.WriteLine("Making Call to F1() " );
try
{
F1();
}
catch
{
Console.WriteLine("Some Exception Occurred.
I don't know what Exception it is and where it Occurred. Sorry!");
}
Console.WriteLine("Successfully returned from F1() " );
}
//002: Set of Function that calls each other
publicvoid F1()
{
Console.WriteLine("Making Call to F2() " );
thrownew System.Exception();
Console.WriteLine("Successfully returned from F2() " );
}
//Client 001: Program Entry
[STAThread]
staticvoid Main(string[] args)
{
//Create the Object and start the Execution
ExceptionsEx app = new ExceptionsEx();
app.StartProgram();
}
}
3. Exception Bubbling
In the above example, we saw thatExceptionis handled in thecatchblock. But, the function call order is simple (Call Stack) that is;StartProgramcalls the function F1 and F1 raisedexceptionis handled in thecatchblock of theStartProgram.
Imagine the situation what happens if there are multiple nested function calls, andexceptionoccurred in the fourth or fifth nested call. Look at the picture below:
F1(): CallsF2within thetryblock and handles the exception incatchblock
F2(): Makes a call to the functionF3. But it neither wraps the call forF3in thetryblock nor has the exception handler
F3(): Raises an Exception
Note, when the exception is thrown by the functionF3, even though the caller isF2, as there is nocatchhandler, the execution comes out ofF2and enters thecatchblock ofF1. Travelling back fromF3->F2->F1is known as Stack Unwind. And exception occurred inF3is handled inF1even when there is no handler atF2is known asExceptionBubbling.
Below is the example that demonstrates theExceptionBubbling:
using System;
namespace ExceptionHandling
{
class ExceptionsEx
{
//001: Start the Program Execution.
publicvoid StartProgram()
{
Console.WriteLine("Making Call to F1() " );
try
{
F1();
}
catch
{
Console.WriteLine("Some Exception Occurred.
I don't know what Exception it is and where it Occurred. Sorry!");
}
Console.WriteLine("Successfully returned from F1() " );
}
//002: Set of Function that calls each other
publicvoid F1()
{
Console.WriteLine("Making Call to F2() " );
F2();
Console.WriteLine("Successfully returned from F2() " );
}
publicvoid F2()
{
Console.WriteLine("Making Call to F2() " );
F3();
Console.WriteLine("Successfully returned from F2() " );
}
publicvoid F3()
{
Console.WriteLine("Inside F3 " );
thrownew System.Exception();
}
//Client 001: Program Entry
[STAThread]
staticvoid Main(string[] args)
{
//Create the Object and start the Execution
ExceptionsEx app = new ExceptionsEx();
app.StartProgram();
}
}
}
4. The Importance of Finally Block
In the above example, we saw that when anexceptionoccurs, we directly jump back on the call stack and travel back searching for thecatchhandler. What about the piece of code that comes next to the exception raising code? If we do releasing resource and releasing the heap memory in the next couple of statements, that will not get reached. Right?
Finallyblock is the solution for this. Now look at the improvedexception-handling skeleton below:
Whatever happens inside thetryblock, it is guaranteed thatfinallyblock gets executed. Hence, all resource releases should be in thefinallyblock. Have a look at the below picture:
Exceptionraised at functionF3is handled in the functionF2. Look at thetryblock, I marked two blocks of code beforeexceptionand code afterexception. It is obvious that when anexceptionraised, the set of code inside the code after exception is never executed. If resources are allocated in code before exception and the allocated resources are released in code after exception, we do have a resource leak for eachexceptionoccurred. Also, think about business logic that needs to revert back apart from the resource leak. This is whyfinallyblock is introduced.
Whether anExceptionoccurs or not, the code insidefinallyblock always gets executed. So you can keep all the cleaning code inside thefinallyblock. The attached sample solution explains the above situation. Put a break point in the very first statement of the functionpublic void StartProgram()and examine the situation explained above. Note, the usage oftryblock with onlyfinallyand withoutcatchin functionF2. Think about it.
5. What is Exception Class?
This class is provided by .NET Framework to handle anyexceptionthat occurred. TheExceptionclass is the base class for all otherExceptionclass provided by .NET Framework.
The exception object has some important properties. Some of then are given below:
Property
Usage
Message
Gives detailed information about the message
StackTrace
Gives the function stack to show whereexceptionis thrown
Targetsite
Shows which method throws theexception
In the previous example, we only used thecatchblock and missed all the above said information. Theexceptionobject is thrown by the piece of code, which raises anExceptionand the handler code catches thatExceptionobject and makes use of the information packed in it. Consider the below example:
void SomefunctionX()
{
thrownew DivideByZeroException();
}
void SomeFunctionY()
{
try
{
SomefunctionX();
}
catch (DivideByZeroException Ex)
{
//Use the Ex here to get information
}
}
The example was shown just to understand from where the object that is used in thecatchblock is coming from. Hope, now you know theexceptioninstance created on thethrowstatement caught in thecatchblock and used. Note that, the base class ofDivideByZeroExceptionisArithmaticException, which is derived from theSystem.Exception. Now the question is, May I useArithmaticExceptionin thecatchblock? Yes. Why not? That is the beauty of polymorphism. When you do, always keep in mind that you are moving from more specialized information thrown to the generalized one.
6. Handler for Multiple Exceptions
A code placed in thetryblock can raise different kinds of exception. It can be say, a Divide by Zero or a Network System Access Denied or a File not exists. How do you handle all the exceptions? The answer is, you can place multiplecatchblocks for atryblock. When an exception is thrown, type of that exception is examined against eachcatchblock. When a match occurs (even polymorph), theexceptionenters into thecatchblock and gets handled.
Let me walk through an example, which will explain the following to you:
Make use ofExceptionobject in thecatchblock
Using multiplecatchblocks for differentexceptions
The importance order of thecatchblocks
1) Program enters the main function and calls the member functionStartProgramafter creating the object of typeExceptionsP2.
2) TheStartProgramfunction makes a call toCalculatefunction. And this call is placed in thetryblock as it is expected that there be some arithmetic exception and possibly a Divide by Zero exception. Twocatchblocks are placed for thetryblock of code. One isDivideByZeroExceptionand other one isSystem.Exception. Inside eachcatchblock, the exception object caught was used to display theExceptionmessage, and function call stack of where theexceptionraised. Below is the code:
//001: Function that Handles the Exception
publicvoid StartProgram()
{
Console.WriteLine("Calling the Function Calculate");
try
{
Calculate();
}
catch (DivideByZeroException Ex)
{
Console.WriteLine("Divide By Zero.
Look at the Call stack for More information");
Console.WriteLine("Packed Message: " + Ex.Message );
Console.WriteLine("Thrown By: " + Ex.TargetSite );
Console.Write("Call Stack: " + Ex.StackTrace );
}
catch (Exception Ex)
{
Console.WriteLine("General Exception Occurred");
Console.WriteLine("Packed Message: " + Ex.Message );
Console.Write("Call Stack: " + Ex.StackTrace );
}
}
3) The calculate is just an intermediate function which makes a call toDivide. Note how the stack rewind and exception bubbling is happening. Below is the function which makes a call to divide, and does not have any Exception handler code:
//002: An intermediate function, just for Demo Purpose
publicvoid Calculate()
{
Console.WriteLine("Calling Divide Function ");
Divide();
}
4) Thedividefunction tries to divide a number by zero. The .NET environment detects the situation and raises the exception for us. Note there is nothrowstatement here. In my previous examples (actually in the previous part), I forced the system to throw anExceptionfor my demonstration purpose. We usually use thethrowstatement for Custom defined exceptions. The .NET environment is smart enough to detect the exception at right time and raise it. Below is the code for divide:
//003: The Divide function which actually raises an Exception
publicvoid Divide()
{
int x = 10;
int y = 0;
y = x / y;
}
7. Closing Notes
TheDivideByZeroExceptionthrown in theDividefunction is caught by theStartProgramfunction. Then theexceptionobject is matched against the firstcatchblock. As there is a match, theexceptionenters thatcatchblock.
What happens ifSystem.Exception catchblock is before theDivideByZeroException? We do enter theSystem.Exception catchblock even though a more perfect match exists. Because, theexceptioncaught is matched from top to bottom. As theSystem.Exceptionis on the top (that is; BeforeDivideByZero) and the caughtException DivideByZeroExceptionis polymorphically aSystem.Exceptionthe execution control just enters theSystem.Exception catchblock.
So always keep in mind to place more specificcatchstatement first and move down with more GeneralizedExceptions. Look at the code below how a smart developer placed hiscatchblock based on what his Team Lead told.
Lead: “The code block may raise aDivideByZeroExceptionor AnyArithmeticException. It is possible to haveFileNotFound Exceptionalso. These are the possibilities ofExceptionI am seeing when I am reviewing your code. But, for safety, try to handle allexceptions in the world and it is OK if it is not more specific”.
That's all, the Lead went to a meeting.
Forget what meeting he is going for, see how the developer placed hiscatchblock:
try
{
// The set of code and function here
// reviewed by an Experienced lead.
}
catch (System.FileNotFoundException Ex)
{
//File Not Found Exception is Different from Divide by zero.
//Look at the Inheritance hierarchy in MSDN for FileNotFoundException
//and DivideByZeroException.
//So I don't care Which one First, FileNotFond or DivideByZero
}
catch( System.DivideByZeroException Ex)
{
//Divide by Zero Exception. Need More Specialized care
}
catch (System.ArithmeticException Ex)
{
// For any ArithmaticException except DivideByZero. Because I already handled it
// before this catch statement
}
catch(System.Exception Ex)
{
//I am not expecting that this would Occur. As per my Lead
//I placed it for safe to handle any Exception in the world
// That derived from Exception.
}
finally
{
//Clean-up code
}
What happens if System.Exception catch block is before the DivideByZeroException? We do enter the System.Exception catch block even though a more perfect match exists. Because, the exception caught is matched from top to bottom. As the System.Exception is on the top (that is; Before DivideByZero) and the caught Exception DivideByZeroException is polymorphically a System.Exception the execution control just enters the System.Exception catch block."
But it is not possible because we can not define System.Exception catch block before the DivideByZeroException catch block otherwise it will generate an error "A previous catch clause already catches all exceptions of this or of super type".
} public static void Main(string[] args) { Class1 a = new Class1(); a.somemethod(); } } }
In above Example See the beauty of Polymorphism. all exception class derived from Exception class, So Exception class reference obj can hold any of the derived class instance object. However (reference obj of exception ) it can call only the property that are of BASE type.
Un-comment above code you will get the file name also. Inner Exception allow us to track Original Exception. Part 40 - C# Tutorial - Exception Handling Part 41 Inner-exceptions The InnerException is a property of an exception. When there are series of exceptions, the most current exception can obtain the prior exception in the InnerException property.
Let us say we have an exception inside a try block throwing an ArgumentException and the catch clause catches it and writes it to a file. However, if the file path is not found, FileNotFoundException is thrown. Let's say that the outside try block catches this exception, but how about the actual ArgumentException that was thrown? Is it lost? No, the InnerException property contains the actual exception. This is the reason for the existence of an InnerException property for any exception.
The InnerException property returns the Exception instance that caused the current exception.
To look at the inner exception, you have to make this program cuase an exception fail. To do that you have 3 options 1. Enter a Character instead of a number (Causes Format Exception) 2. Or Enter a very big number that an interger cannot hold (Causes Over Flow Exception) 3. Or Enter Zero for Second Number (Causes Divide By Zero Exception) using System; using System.IO; class ExceptionHandling { public static void Main() { try { try { Console.WriteLine("Enter First Number"); int FN = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Second Number"); int SN = Convert.ToInt32(Console.ReadLine());
int Result = FN / SN; Console.WriteLine("Result = {0}", Result); } catch (Exception ex) { string filePath = @"C:\Sample Files\Log.txt"; if (File.Exists(filePath)) { StreamWriter sw = newStreamWriter(filePath); sw.Write(ex.GetType().Name + ex.Message + ex.StackTrace); sw.Close(); Console.WriteLine("There is a problem! Plese try later"); } else { //To retain the original exception pass it as a parameter //to the constructor, of the current exception throw newFileNotFoundException(filePath + " Does not Exist", ex); } } } catch (Exception ex) { //ex.Message will give the current exception message Console.WriteLine("Current or Outer Exception = " + ex.Message);
//Check if inner exception is not null before accessing Message property //else, you may get Null Reference Excception if(ex.InnerException != null) { Console.WriteLine("Inner Exception = ", ex.InnerException.Message); } } } } **********************
Exception.InnerException
Property
Gets
theExceptioninstance that caused the current exception.
Type:System.Exception
An instance ofExceptionthat describes the error that caused
the current exception. TheInnerExceptionproperty
returns the same value as was passed into the constructor, or a null reference
(Nothingin
Visual Basic) if the inner exception value was not supplied to the constructor.
This property is read-only.
When
an exceptionXis
thrown as a direct result of a previous exceptionY,
theInnerExceptionproperty ofXshould contain a reference toY.
Use
theInnerExceptionproperty to obtain the set of
exceptions that led to the current exception.
You
can create a new exception that catches an earlier exception. The code that
handles the second exception can make use of the additional information from
the earlier exception to handle the error more appropriately.
Suppose
that there is a function that reads a file and formats the data from that file.
In this example, as the code tries to read the file, anIOExceptionis
thrown. The function catches theIOExceptionand
throws aFileNotFoundException. TheIOExceptioncould
be saved in theInnerExceptionproperty
of theFileNotFoundException,
enabling the code that catches theFileNotFoundExceptionto examine what causes the initial
error.
TheInnerExceptionproperty, which holds a reference to the
inner exception, is set upon initialization of the exception object.
public Exception InnerException { get; }
InnerException is Type of
Exception which is base class of any Exception class in .net framework. See
below
using System;
namespace KudVenkatCsharp
{
publicclassMyAppException : ApplicationException
{
publicException
currentexception{get;set;}
public MyAppException(String message)
{ }//Here in below constructer we passed the
Excetion inner that means it will initilize the Base class Innerexcetion
property. So If you want to keep track on the previous exception in the current
excetion, So pass Exception instance in the constructer of current exception.
previous excetion you will get as the Base excetion type since you send that
excetion to base excetion class. You can get the inner excetion in the parent
child relationship only.
//Why ? /Two excption occured one you hold as
the Derived class excetion and other one you pass to the Base class Exception
which can hold any exception that is why we shud derive our class from
ApplicationException or Excetion, by default .net framework excetion inherited
from Exception class.
public MyAppException(String message, Exception inner) : base(message,inner) {
}
publicvoid ThrowInner()
{
thrownewMyAppException("Inner
exception. First Excetion .ThrowInner()");
}
publicvoid CatchInner()
{
try
{
this.ThrowInner();
}
catch (Exception e)//this ( MyAppException) exception we
pass to base class Exception class to hold its reference.
Console.WriteLine("Inner
Exception is {0}", e.StackTrace);
Console.ReadLine();
}
}
}
}
}
The InnerException is a property of an exception. When there
are series of exceptions, the most current exception can obtain the prior
exception in the InnerException property.
Let us say we have an exception inside a try
block throwing an ArgumentException and the catch clause catches it and writes
it to a file. However, if the file path is not found, FileNotFoundException is
thrown. Let's say that the outside try block catches this exception, but how
about the actual ArgumentException that was thrown? Is it lost? No, the
InnerException property contains the actual exception. This is the reason for
the existence of an InnerException property for any exception.
The following example, Listing 7.13, demonstrates the concept
of checking the inner exception.
Listing 7.13: Exception13.cs, InnerException Example
usingSystem;
usingSystem.IO;
catch(ArgumentExceptione)
{ //make sure this path does not exist if(File.Exists("file://Bigsky//log.txt%22)%20==%20false) ==false)
{ thrownewFileNotFoundException("File
Not found when trying to write argument exception to the file", e);
}
}
}
The InnerException
property returns the Exception instance that caused the current exception.
To look at the inner exception, you have to make this program cuase
an exception fail. To do that you have 3 options 1. Enter a Character instead of a number (Causes Format Exception) 2. Or Enter a very big number that an interger cannot hold (Causes
Over Flow Exception) 3. Or Enter Zero for Second Number (Causes Divide By Zero
Exception)
Part 41 - C#
Tutorial - Inner Exceptions
using System; using System.IO; class ExceptionHandling { public static void Main() { try { try { Console.WriteLine("Enter First Number"); int FN = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Second Number"); int SN = Convert.ToInt32(Console.ReadLine());
int Result = FN / SN; Console.WriteLine("Result = {0}", Result); } catch (Exception ex) { string filePath = @"C:\Sample Files\Log.txt"; if (File.Exists(filePath))
{ StreamWriter sw = newStreamWriter(filePath);
sw.Write(ex.GetType().Name + ex.Message + ex.StackTrace);
sw.Close(); Console.WriteLine("There is a problem! Plese try later");
} else
{ //To
retain the original exception pass it as a parameter
//to the constructor, of the
current exception throw newFileNotFoundException(filePath + " Does not Exist", ex);
} } } catch (Exception ex) { //ex.Message will give the current
exception message Console.WriteLine("Current or Outer Exception = " + ex.Message);
//Check if inner exception is not null
before accessing Message property
//else, you may get Null Reference Excception if(ex.InnerException != null) { Console.WriteLine("Inner Exception = ", ex.InnerException.Message); } } } }
Difference between throw,Throw Ex
When you use the throw
with an empty parameter, you are re-throwing the last exception. When you throw
the existing exception you are creating a new exception. What's the difference? Simple: the stack trace. The empty parameter re-throw and keeps the
existing stack list, the parametered version creates a new stack trace to the
point of the throw. For debugging, the empty version tells you where the error
actually occurred, the parametered version discards that.
In Throw, the original exception stack trace
will be retained. To keep the original stack trace information, the correct
syntax is 'throw' without specifying an exception.
Declaration of throw
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw;
}
Throw ex
In Throw ex, the original stack trace
information will get override and you will lose the original exception stack
trace. I.e. 'throw ex' resets the stack trace.
Declaration of throw ex
try
{
// do some operation that can fail
}
catch (Exception ex)
{
// do some local cleanup
throw ex;
}
}
·throw ex resets the stack trace (so your errors would appear to
originate from HandleException)
·throw doesn't - the original offender would be preserved.
You can see that in Exception 1, the stack trace goes back to
the DivByZero() method, whereas in Exception 2 it does not.
Take note, though, that the line number shown in ThrowException1() and ThrowException2() is the line number of the throw statement, not the line
number of the call to DivByZero(), which probably makes sense now that I think about it a
bit...