SlideShare a Scribd company logo
1 of 8
1. Exceptions area constructin the .NET Framework thatare (ideally) used to
indicate an unexpected state in executing code.
For example, when working with a databasethe underlying ADO.NETcode
that communicates with the database raises an exception if the database is
offline or if the databasereports an error when executing a query. Similarly,
if you attempt to castuser input fromone type to another - say froma
string to an integer - but the user's inputis not valid, an exception will be
thrown. You can also raise exceptions fromyour own code by using
the Throw keyword.
2. When an exception is thrown it is passed up the call stack. That is,
if MethodA calls MethodB, and then MethodB raises an
exception, MethodA is given the opportunity to execute code in response
to the exception. Specifically, MethodA can do one of two things: it
can catch the exception (using a Try..Catch block) and execute code in
responseto the exception being throw; or it can ignorethe exception and
let it percolate up the call stack. If the exception is percolated up the call
stack - either by MethodA not catching the exception or by MethodA re-
throwing the exception - then the exception information will be passed up
to the method that called MethodA. If no method in the call stack handles
the exception then it will eventually reach the ASP.NET runtime, which will
display the configured error page as shown in the fig below.
3. This kind of error is the un handled error ,means we can not handle the
exception .
4. How to overcome this type of error :
Whenever an unhandled exception occurs, theASP.NETruntime displays its
configured error page. (An unhandled exception is an exception that is not caught
and handled by some method in the call stack when the exception is raised. If no
method in the call stack catches the exception then it percolates all the way up to
the ASP.NETruntime, which then displays the error page as shown above.)
The error page displayed by the ASP.NET runtime depends on two factors:
 Whether the website is being visited locally or remotely, and
 The <customErrors> configuration in Web.config.
5. While the Yellow Screen of Death error page is acceptable in the
development environment, displaying such an error page in production to
real users smacks of an unprofessionalwebsite. Instead, your ASP.NET
application should usea custom error page. A customerror page is a user-
friendly error page that you create in your project. Unlike the Yellow Screen
of Death error page, a customerror page can match the look and feel of
your existing website and explain to the user that there was a problem and
providesuggestions or steps for the user to take as shown below.
6.For this purposeupdate the web.config file as follow
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="pages/Error.aspx" />
</system.web>
</configuration>
=========================================================================================
<customErrors defaultRedirect="url"
mode="On|Off|RemoteOnly">
<error statusCode="statuscode"
redirect="url"/>
</customErrors>
Required Attribute
Attribute Option Description
Mode Specifieswhethercustomerrorsare enabled,disabled,or
shownonlytoremote clients.
On Specifiesthatcustomerrorsare enabled.If
no defaultRedirectisspecified,userssee agenericerror.
Off Specifiesthatcustomerrorsare disabled.Thisallowsdisplayof
detailederrors.
RemoteOnly Specifiesthatcustomerrorsare shownonly toremote clients
and ASP.NETerrorsare showntothe local host.Thisisthe
default.
Optional Attribute
Attribute Description
defaultRedirect Specifiesthe defaultURLto directa browsertoif an error occurs.
WhendefaultRedirectisnotspecified,agenericerrorisdisplayedinstead.The URL
may be absolute (forinstance,http://www.contoso.com/ErrorPage.htm)oritmay
be relative.A relative URLsuchas /ErrorPage.htmisrelative tothe Web.configfile
that specifiedthedefaultRedirectURL,not tothe Webpage in whichthe error
occurred.A URL startingwitha tilde (~),suchas~/ErrorPage.htm,meansthatthe
specifiedURLis relative tothe rootpath of the application.
Subtag
Subtag Description
<error> The error subtag can appearmultiple times.Eachappearance definesone custom
error condition.
If someunhandled exceptions come then the page will be reditected to the custo
error page we shall usein the application instead of runtime generated error
page.
7.HandledExceptions :How to track while in production and record the error
messagein notepad with details like time and error message.
i. The handled exceptions are the exceptions which wecome across
many time in the solution.We can see thoseerrors when we are in
running and by applying the debugger. But when the application is
in production we can’t see those errors by applying debuggers .
ii. So we need to create the notepad and all the error details, time
will be saned in the notepad .so that wecan get the notepad of
date and can see the error details.
iii. For This we need to create a folder at server side . The code for
the sameshould be in the startpage of the application .
 Code to create the Folder
/// <summary>
/// fuction to createfolder andfilefor exceptionhandling
/// </summary>
privatevoid CreateErrorFolder()
{
stringerrorFolder=AppDomain.CurrentDomain.BaseDirectory +"ErrorDetails";
// Directory for thethePDF documentto be shown
DirectoryInfo directory=newDirectoryInfo(errorFolder);
try
{
if (!directory.Exists)
{
directory.Create();
}
}
catch (Exceptionex)
{
string msg=ex.ToString();
}
}
iv.We need to call the abovefunction in page load
protected void Page_Load(objectsender,EventArgs e)
{
CreateErrorFolder();
}
v.This will create the folder named ErrorDetails in the currentdirectory.
vi. Create one .cs file in dal transaction layer .
we need to create the .cs file in dal transaction so that we can usethat file in BLL
and Code behind of each page.sincewe give reference of DAL to BLL and BLL to
Code Behind.
Vii.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Linq;
using System.Web;
using System.Globalization;
namespace DemoDAL
{
public class ErrorHandler
{
public static void WriteError(string errorMessage)
{
try
{
string path = "~ErrorDetails" + DateTime.Today.ToString("dd-MMM-yy")
+ ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w =
File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("rnStart Message : ");
w.WriteLine("{0}",
DateTime.Now.ToString(CultureInfo.InvariantCulture));
w.WriteLine("Page : " +
System.Web.HttpContext.Current.Request.Url.ToString());
w.WriteLine("nError Message: " + errorMessage);
w.WriteLine("__________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}
}
}
This .cs file contains the public static void WriteError(string errorMessage) function
This function will create a notepad with title of the current date ,It will take the
present time and will write the error details there .
Ex.
Start Message :
06/28/2014 18:17:57
Page : http://localhost:4766/432/Pages/Demo.aspx/PopulateDemo
Error Message: System.DivideByZeroException: Attempted to divide by zero.
at Demo.UI.Pages.HomeDemo.PopulateDemo(Int32 IDDemo) in
C:UsersDemoPagesHomeDemo.aspx.cs:line 45
Vii. In order to call the above function and pass the error
message to that function we have to write all functions in
Code behond with try… catch Blocks .
Ix. In the catch block,the error messageis taken and sent it to WriteError function.
Where it will be printed in notepad.
catch (Exception ex)
{
string msg = Convert.ToString(ex);
ErrorHandler.WriteError(msg);
throw ex;
}

More Related Content

What's hot

Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentKetan Raval
 
HTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMHTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMDean Hamstead
 
Using correlation in loadrunner 80
Using correlation in loadrunner 80Using correlation in loadrunner 80
Using correlation in loadrunner 80medsherb
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scriptsch samaram
 
Data validation in web applications
Data validation in web applicationsData validation in web applications
Data validation in web applicationssrkirkland
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedBG Java EE Course
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handlingMinh Hoang
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019GoQA
 
Don't Ignore Your Errors!
Don't Ignore Your Errors!Don't Ignore Your Errors!
Don't Ignore Your Errors!Mary Jo Sminkey
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-ChallengesJose Mendez
 

What's hot (17)

Best Coding Practices For Android Application Development
Best Coding Practices For Android Application DevelopmentBest Coding Practices For Android Application Development
Best Coding Practices For Android Application Development
 
Java scipt
Java sciptJava scipt
Java scipt
 
Jsp
JspJsp
Jsp
 
HTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PMHTML::FormFu talk for Sydney PM
HTML::FormFu talk for Sydney PM
 
Using correlation in loadrunner 80
Using correlation in loadrunner 80Using correlation in loadrunner 80
Using correlation in loadrunner 80
 
Basics java scripts
Basics java scriptsBasics java scripts
Basics java scripts
 
Data validation in web applications
Data validation in web applicationsData validation in web applications
Data validation in web applications
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Node.js exception handling
Node.js exception handlingNode.js exception handling
Node.js exception handling
 
ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
Form Validation
Form ValidationForm Validation
Form Validation
 
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS»  QADay 2019
МИХАЙЛО БОДНАРЧУК «SuperCharged End to End Testing with CodeceptJS» QADay 2019
 
Don't Ignore Your Errors!
Don't Ignore Your Errors!Don't Ignore Your Errors!
Don't Ignore Your Errors!
 
Chapter 9
Chapter 9Chapter 9
Chapter 9
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
 
Ajaxppt
AjaxpptAjaxppt
Ajaxppt
 

Similar to Exception handling

SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5Ben Abdallah Helmi
 
Monitoring, troubleshooting,
Monitoring, troubleshooting,Monitoring, troubleshooting,
Monitoring, troubleshooting,aspnet123
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questionsAkhil Mittal
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable coden|u - The Open Security Community
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPAli Shah
 
People code events 1
People code events 1People code events 1
People code events 1Samarth Arora
 
PHP Exception handler
PHP Exception handlerPHP Exception handler
PHP Exception handlerRavi Raj
 
Debugging NET Applications With WinDBG
Debugging  NET Applications With WinDBGDebugging  NET Applications With WinDBG
Debugging NET Applications With WinDBGCory Foy
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application SecurityChris x-MS
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsKai Cui
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practicesYoni Goldberg
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Massimo Oliviero
 
Lightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error HandlingLightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error HandlingNick Burwell
 
Lightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesLightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesGaurav Jain
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 

Similar to Exception handling (20)

SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
 
Monitoring, troubleshooting,
Monitoring, troubleshooting,Monitoring, troubleshooting,
Monitoring, troubleshooting,
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
C sharp and asp.net interview questions
C sharp and asp.net interview questionsC sharp and asp.net interview questions
C sharp and asp.net interview questions
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable codenullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
nullcon 2011 - Reversing MicroSoft patches to reveal vulnerable code
 
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISPMCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP
 
People code events 1
People code events 1People code events 1
People code events 1
 
PHP Exception handler
PHP Exception handlerPHP Exception handler
PHP Exception handler
 
Debugging NET Applications With WinDBG
Debugging  NET Applications With WinDBGDebugging  NET Applications With WinDBG
Debugging NET Applications With WinDBG
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
 
Node.JS error handling best practices
Node.JS error handling best practicesNode.JS error handling best practices
Node.JS error handling best practices
 
Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)Advanced iOS Debbuging (Reloaded)
Advanced iOS Debbuging (Reloaded)
 
Lightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error HandlingLightning Talk: JavaScript Error Handling
Lightning Talk: JavaScript Error Handling
 
Lightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesLightning page optimization &amp; best practices
Lightning page optimization &amp; best practices
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 

Exception handling

  • 1. 1. Exceptions area constructin the .NET Framework thatare (ideally) used to indicate an unexpected state in executing code. For example, when working with a databasethe underlying ADO.NETcode that communicates with the database raises an exception if the database is offline or if the databasereports an error when executing a query. Similarly, if you attempt to castuser input fromone type to another - say froma string to an integer - but the user's inputis not valid, an exception will be thrown. You can also raise exceptions fromyour own code by using the Throw keyword. 2. When an exception is thrown it is passed up the call stack. That is, if MethodA calls MethodB, and then MethodB raises an exception, MethodA is given the opportunity to execute code in response to the exception. Specifically, MethodA can do one of two things: it can catch the exception (using a Try..Catch block) and execute code in responseto the exception being throw; or it can ignorethe exception and let it percolate up the call stack. If the exception is percolated up the call stack - either by MethodA not catching the exception or by MethodA re- throwing the exception - then the exception information will be passed up to the method that called MethodA. If no method in the call stack handles the exception then it will eventually reach the ASP.NET runtime, which will display the configured error page as shown in the fig below. 3. This kind of error is the un handled error ,means we can not handle the exception .
  • 2. 4. How to overcome this type of error : Whenever an unhandled exception occurs, theASP.NETruntime displays its configured error page. (An unhandled exception is an exception that is not caught and handled by some method in the call stack when the exception is raised. If no method in the call stack catches the exception then it percolates all the way up to the ASP.NETruntime, which then displays the error page as shown above.) The error page displayed by the ASP.NET runtime depends on two factors:  Whether the website is being visited locally or remotely, and  The <customErrors> configuration in Web.config.
  • 3. 5. While the Yellow Screen of Death error page is acceptable in the development environment, displaying such an error page in production to real users smacks of an unprofessionalwebsite. Instead, your ASP.NET application should usea custom error page. A customerror page is a user- friendly error page that you create in your project. Unlike the Yellow Screen of Death error page, a customerror page can match the look and feel of your existing website and explain to the user that there was a problem and providesuggestions or steps for the user to take as shown below. 6.For this purposeupdate the web.config file as follow <configuration> <system.web> <customErrors mode="On" defaultRedirect="pages/Error.aspx" /> </system.web> </configuration>
  • 4. ========================================================================================= <customErrors defaultRedirect="url" mode="On|Off|RemoteOnly"> <error statusCode="statuscode" redirect="url"/> </customErrors> Required Attribute Attribute Option Description Mode Specifieswhethercustomerrorsare enabled,disabled,or shownonlytoremote clients. On Specifiesthatcustomerrorsare enabled.If no defaultRedirectisspecified,userssee agenericerror. Off Specifiesthatcustomerrorsare disabled.Thisallowsdisplayof detailederrors. RemoteOnly Specifiesthatcustomerrorsare shownonly toremote clients and ASP.NETerrorsare showntothe local host.Thisisthe default. Optional Attribute Attribute Description defaultRedirect Specifiesthe defaultURLto directa browsertoif an error occurs. WhendefaultRedirectisnotspecified,agenericerrorisdisplayedinstead.The URL may be absolute (forinstance,http://www.contoso.com/ErrorPage.htm)oritmay be relative.A relative URLsuchas /ErrorPage.htmisrelative tothe Web.configfile that specifiedthedefaultRedirectURL,not tothe Webpage in whichthe error occurred.A URL startingwitha tilde (~),suchas~/ErrorPage.htm,meansthatthe specifiedURLis relative tothe rootpath of the application.
  • 5. Subtag Subtag Description <error> The error subtag can appearmultiple times.Eachappearance definesone custom error condition. If someunhandled exceptions come then the page will be reditected to the custo error page we shall usein the application instead of runtime generated error page. 7.HandledExceptions :How to track while in production and record the error messagein notepad with details like time and error message. i. The handled exceptions are the exceptions which wecome across many time in the solution.We can see thoseerrors when we are in running and by applying the debugger. But when the application is in production we can’t see those errors by applying debuggers . ii. So we need to create the notepad and all the error details, time will be saned in the notepad .so that wecan get the notepad of date and can see the error details. iii. For This we need to create a folder at server side . The code for the sameshould be in the startpage of the application .  Code to create the Folder /// <summary> /// fuction to createfolder andfilefor exceptionhandling /// </summary> privatevoid CreateErrorFolder() { stringerrorFolder=AppDomain.CurrentDomain.BaseDirectory +"ErrorDetails"; // Directory for thethePDF documentto be shown DirectoryInfo directory=newDirectoryInfo(errorFolder); try { if (!directory.Exists) { directory.Create(); }
  • 6. } catch (Exceptionex) { string msg=ex.ToString(); } } iv.We need to call the abovefunction in page load protected void Page_Load(objectsender,EventArgs e) { CreateErrorFolder(); } v.This will create the folder named ErrorDetails in the currentdirectory. vi. Create one .cs file in dal transaction layer . we need to create the .cs file in dal transaction so that we can usethat file in BLL and Code behind of each page.sincewe give reference of DAL to BLL and BLL to Code Behind. Vii. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Linq; using System.Web; using System.Globalization; namespace DemoDAL { public class ErrorHandler { public static void WriteError(string errorMessage) { try { string path = "~ErrorDetails" + DateTime.Today.ToString("dd-MMM-yy") + ".txt"; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); }
  • 7. using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { w.WriteLine("rnStart Message : "); w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)); w.WriteLine("Page : " + System.Web.HttpContext.Current.Request.Url.ToString()); w.WriteLine("nError Message: " + errorMessage); w.WriteLine("__________________________"); w.Flush(); w.Close(); } } catch (Exception ex) { WriteError(ex.Message); } } } } This .cs file contains the public static void WriteError(string errorMessage) function This function will create a notepad with title of the current date ,It will take the present time and will write the error details there . Ex. Start Message : 06/28/2014 18:17:57 Page : http://localhost:4766/432/Pages/Demo.aspx/PopulateDemo Error Message: System.DivideByZeroException: Attempted to divide by zero. at Demo.UI.Pages.HomeDemo.PopulateDemo(Int32 IDDemo) in C:UsersDemoPagesHomeDemo.aspx.cs:line 45 Vii. In order to call the above function and pass the error message to that function we have to write all functions in Code behond with try… catch Blocks .
  • 8. Ix. In the catch block,the error messageis taken and sent it to WriteError function. Where it will be printed in notepad. catch (Exception ex) { string msg = Convert.ToString(ex); ErrorHandler.WriteError(msg); throw ex; }