SlideShare a Scribd company logo
Chapter 5 Exception Handling and Validation Controls No one is so brave that he is not perturbed by the unexpected. Julius Caesar,  De Bello Gallico , 6.39.
Overview Exception handling in C# Exception handling in ASP.NET Validation controls
Error Handling Even the best written Web application can suffer from runtime errors.  Most complex Web applications must interact with external systems such as databases, Web services, RSS feeds, email servers, file system, and other externalities that are beyond your control.  A failure in any one of these systems means that your application can also no longer run successfully.  It is vitally important that your applications can gracefully handle such problems.
.NET Exception Handling When an error occurs, something called an  exception  is raised, or  thrown  in the nomenclature of .NET.  When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error.  When thrown, an exception can be handled by the application or by ASP.NET itself.
Exception Handling Model In the .NET exception handling model, exceptions are represented as objects.  The ancestor class for all exceptions is  Exception .  This class has many subclasses.  Every  Exception  object contains information about the error.
Default Error Page When an exception is raised but not handled by the application, ASP.NET displays the  default error page .  This page displays: the exception message the exception type the line that it occurred on stack trace
Default Error Page
Handling Exceptions Although this ASP.NET default error page is quite useful when developing and debugging an application, you might not always want to display this page when an exception occurs.  Instead, you might want to  handle  the exception.  There are three different ways or levels where you can do so: At the class level  At the page level At the application level.
Class level exception handling All .NET languages provide a mechanism for separating regular program code from exception handling code.  In C#, this is accomplished via the  try…catch  block.  If a runtime error occurs during the execution of any code placed within a try block, the program does not crash … … but instead tries to execute the code contained in one of the catch blocks.
try…catch block try { double dVal1 = Convert.ToDouble(txtValue1.Text); double dVal2 = Convert.ToDouble(txtValue2.Text); double result = dVal1 / dVal2; labMessage.Text = txtValue1.Text + "/" + txtValue2.Text; labMessage.Text += "=" + result; } catch (FormatException ex1) { labMessage.Text = "Please enter a valid number"; } catch (Exception ex2) { labMessage.Text = "Unable to compute a value with these values"; }
finally block There may be times when you want to execute some block of code regardless of whether an exception occurred.  The classic example is closing a database connection no matter whether the SQL operation was successful or generated an exception.  In such a case, you can use the optional  finally  block
finally block try { // Open a database connection // Execute SQL statement } catch (DbException ex) { // Handle database exception } finally  { // Close database connection if it exists }
Cost of Exceptions Throwing exceptions is relatively expensive in terms of CPU cycles and resource usage. As a result, one should try to use exceptions to handle only exceptional situations.  If your code relies on throwing an exception as part of its normal flow, you should refactor the code to avoid exceptions, perhaps by using a return code or some other similar mechanism instead.
Using Exceptions try  { SomeBusinessObject.Login(email); // Other code dependent upon a successful login } catch (Exception ex) { // Display message that email was not found } bool okay = SomeBusinessObject.Login(email); if (! okay) { // Display error message on page  } else { // Other code dependent upon a successful login } bad good
Exception Handling Strategies  If you design your code so that exceptions are thrown only in truly exceptional situations, what do you when one of these exceptional exceptions occurs?
Exception Handling Strategies  Possible strategies: “ Swallow” the exception by catching and ignoring the exception by continuing normal execution. Almost never appropriate. Completely handle the exception within the catch block. Ignore the exception by not catching it (and thus let some other class handle it).  Catch the exception and rethrow it for some other class to handle it.
Exception Handling Strategies  You may want to know when an exception occurs in a production application so that you can change the code to prevent it from occurring in the future.  In this case, you might not want to catch the exception but instead let some other class “higher” in the calling stack handle it, perhaps by recording the exception to some type of exception log.  Even if you are not recording an exception log, you should remember that in general, you should not catch exceptions in a method unless it can handle them, such as by: logging exception details,  performing some type of page redirection, retrying the operation,  performing some other sensible action.
Page Level Exception Handling ASP.NET allows the developer to handle errors on a page basis via the page’s  Page_Error  event handler.  The  Page_Error  event handler is called whenever an uncaught exception occurs during the exception of the page.
Page_Error event handler public partial class PageExceptionTest : System.Web.UI.Page { … private void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Response.Write(&quot;<h1>An error has occurred</h1>&quot;); Response.Write(&quot;<h2>&quot; + ex.Message + &quot;</h2>&quot;); Response.Write(&quot;<pre>&quot; + ex.StackTrace + &quot;</pre>&quot;); Context.ClearError(); } }
Application level exception handling There are two different ways that you can handle an exception at the application level:  using a  Application_Error  event handler using the ASP.NET error page redirection mechanism.
Using the Application_Error Handler ASP.NET allows the developer to handle errors on an application-wide basis via the  Application_Error  event handler.  This handler resides in the application’s  Global.asax  file and is often the preferred location to handle uncaught exceptions in an application.  Because you often want to do the same thing for all unhandled exceptions in your application.  Rather than have the same type of error-logging code on every single page, it makes sense to centralize this code into a single spot.
Custom Error Page To use a custom error page, you can change the settings of the  <customErrors>  element in the  Web.config  file.  In this element, you can specify the custom page that is to be displayed. <system.web> <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; /> … </system.web>
Custom Error Pages You can create custom error pages for different HTTP error codes.  For example, a common feature of many Web sites is to provide custom HTTP 404 (requested page not found) and HTTP 500 (server error) error pages.  You can specify custom pages for HTTP error codes within the  <customErrors>  element.  <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; > <error statusCode=&quot;404&quot; redirect=&quot;custom404.aspx&quot; /> <error statusCode=&quot;500&quot; redirect=&quot;custom500.aspx&quot; /> </customErrors>
Validation Server Controls  These are a special type of Web server control.  They significantly reduce some of the work involved in validating user data.  They are used to validate or verify that certain input server controls (such as  TextBox ,  RadioButtonList , or  DropDownList ) contain correct data.
Validation Server Controls  RequiredFieldValidator   Ensures that the input control is not empty. CompareValidator Compares a user entry against another value or control.  RangeValidator   Checks if a user entry is between a lower and upper boundary. RegularExpressionValidator   Checks if a user entry matches a pattern defined by a regular expression  CustomValidator   Checks a user entry using custom validation logic.  ValidationSummary   Displays the error messages from all validation controls in a single location.
Validation Server Controls  You use validation server controls as you do other server controls.  That is, you add the markup to your .aspx file where you would like an error indicator to be displayed (typically adjacent to the field it is validating).  Each validation control references another input server control elsewhere on the page.  <asp:TextBox ID=&quot;txtUserName&quot; runat=&quot;server&quot; /> <asp:RequiredFieldValidator Id=&quot;reqUser&quot; runat=&quot;server&quot;  ControlToValidate=&quot;txtUserName&quot;  Text=&quot;Please enter a User Name&quot; />
Form Validation Process  When a form that uses these validators is submitted, the user’s input is validated first by using Javascript on the client side if enabled and if supported by the browser.  If there is an error, an error message is displayed without a round-trip to the server.  If no error (or no Javascript or if client validation is disabled), the data is passed to the server and the data is checked once again on the server side.  If the data is not valid, an error message is generated and ultimately sent back to the browser (along with all the other form data).
Form Validation Process  Why is both client-side and server-side data validation necessary?  Client-side validation is useful because it reduces round-trips to the server.  This provides immediate feedback to the user as well as improves server performance.  Client-side validation by itself is not sufficient. The user could be using a browser that does not support scripting. that is, using an ancient browser or, more commonly, has scripting turned off via the browser preferences.  Client-side scripting is also potentially vulnerable to “script exploits.”
Form Validation Process User data must thus be validated on both the client and the server side.  Validation controls automatically generate the Javascript necessary for client-side validation as well as perform, behind the scenes, the server-side validation.
Validation Controls See pages 280-308
Ad

Recommended

Introduction to ado.net
Introduction to ado.net
Paneliya Prince
 
android sqlite
android sqlite
Deepa Rani
 
Simple object access protocol(soap )
Simple object access protocol(soap )
balamurugan.k Kalibalamurugan
 
What Is Cloud Computing? | Cloud Computing For Beginners | Cloud Computing Tr...
What Is Cloud Computing? | Cloud Computing For Beginners | Cloud Computing Tr...
Simplilearn
 
Cloud service providers
Cloud service providers
AgnihotriGhosh1
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
Pallepati Vasavi
 
Entity framework code first
Entity framework code first
Confiz
 
Ado.Net Tutorial
Ado.Net Tutorial
prabhu rajendran
 
ADO .Net
ADO .Net
DrSonali Vyas
 
Technology Behind IoT (JNTUK - Unit - 1)
Technology Behind IoT (JNTUK - Unit - 1)
FabMinds
 
IoT ecosystem
IoT ecosystem
Md. Shamsul Haque
 
Attribute oriented analysis
Attribute oriented analysis
Hirra Sultan
 
Iot in healthcare
Iot in healthcare
GauravBiswas9
 
Exception Handling in VB.Net
Exception Handling in VB.Net
rishisingh190
 
Introduction to .net framework
Introduction to .net framework
Arun Prasad
 
J2 ee container & components
J2 ee container & components
Keshab Nath
 
Introduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
DOT Net overview
DOT Net overview
chandrasekhardesireddi
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Ahsanul Karim
 
IOT Platform Design Methodology
IOT Platform Design Methodology
poonam kumawat
 
two tier and three tier
two tier and three tier
Kashafnaz2
 
ERP solution for eCommerce Business
ERP solution for eCommerce Business
Globalteckz
 
Query Processing, Query Optimization and Transaction
Query Processing, Query Optimization and Transaction
Prabu U
 
Google Maps in Android
Google Maps in Android
Mobile 2.0 Europe
 
Dbms viva questions
Dbms viva questions
Balveer Rathore
 
Cloud computing security issues and challenges
Cloud computing security issues and challenges
Dheeraj Negi
 
The Internet of Things (IoT) PDF
The Internet of Things (IoT) PDF
Nigel Tebbutt 奈杰尔 泰巴德
 
Cloud security
Cloud security
François Boucher
 
ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828
Viral Patel
 
Exception handling in asp.net
Exception handling in asp.net
LearningTech
 

More Related Content

What's hot (20)

ADO .Net
ADO .Net
DrSonali Vyas
 
Technology Behind IoT (JNTUK - Unit - 1)
Technology Behind IoT (JNTUK - Unit - 1)
FabMinds
 
IoT ecosystem
IoT ecosystem
Md. Shamsul Haque
 
Attribute oriented analysis
Attribute oriented analysis
Hirra Sultan
 
Iot in healthcare
Iot in healthcare
GauravBiswas9
 
Exception Handling in VB.Net
Exception Handling in VB.Net
rishisingh190
 
Introduction to .net framework
Introduction to .net framework
Arun Prasad
 
J2 ee container & components
J2 ee container & components
Keshab Nath
 
Introduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
DOT Net overview
DOT Net overview
chandrasekhardesireddi
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Ahsanul Karim
 
IOT Platform Design Methodology
IOT Platform Design Methodology
poonam kumawat
 
two tier and three tier
two tier and three tier
Kashafnaz2
 
ERP solution for eCommerce Business
ERP solution for eCommerce Business
Globalteckz
 
Query Processing, Query Optimization and Transaction
Query Processing, Query Optimization and Transaction
Prabu U
 
Google Maps in Android
Google Maps in Android
Mobile 2.0 Europe
 
Dbms viva questions
Dbms viva questions
Balveer Rathore
 
Cloud computing security issues and challenges
Cloud computing security issues and challenges
Dheeraj Negi
 
The Internet of Things (IoT) PDF
The Internet of Things (IoT) PDF
Nigel Tebbutt 奈杰尔 泰巴德
 
Cloud security
Cloud security
François Boucher
 
Technology Behind IoT (JNTUK - Unit - 1)
Technology Behind IoT (JNTUK - Unit - 1)
FabMinds
 
Attribute oriented analysis
Attribute oriented analysis
Hirra Sultan
 
Exception Handling in VB.Net
Exception Handling in VB.Net
rishisingh190
 
Introduction to .net framework
Introduction to .net framework
Arun Prasad
 
J2 ee container & components
J2 ee container & components
Keshab Nath
 
Introduction to ASP.NET
Introduction to ASP.NET
Rajkumarsoy
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Ahsanul Karim
 
IOT Platform Design Methodology
IOT Platform Design Methodology
poonam kumawat
 
two tier and three tier
two tier and three tier
Kashafnaz2
 
ERP solution for eCommerce Business
ERP solution for eCommerce Business
Globalteckz
 
Query Processing, Query Optimization and Transaction
Query Processing, Query Optimization and Transaction
Prabu U
 
Cloud computing security issues and challenges
Cloud computing security issues and challenges
Dheeraj Negi
 

Viewers also liked (8)

ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828
Viral Patel
 
Exception handling in asp.net
Exception handling in asp.net
LearningTech
 
461
461
Jesus Valenzuela
 
Exception
Exception
abhay singh
 
Interfaces & Packages V2
Interfaces & Packages V2
Dr Anjan Krishnamurthy
 
Servlets lecture2
Servlets lecture2
Tata Consultancy Services
 
Data Validation Victories: Tips for Better Data Quality
Data Validation Victories: Tips for Better Data Quality
Safe Software
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
Volker Hirsch
 
ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828
Viral Patel
 
Exception handling in asp.net
Exception handling in asp.net
LearningTech
 
Data Validation Victories: Tips for Better Data Quality
Data Validation Victories: Tips for Better Data Quality
Safe Software
 
TEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
Volker Hirsch
 
Ad

Similar to ASP.NET 05 - Exception Handling And Validation Controls (20)

Exception handling
Exception handling
Mahesh Pachbhai
 
Exception handling in asp.net
Exception handling in asp.net
Neelesh Shukla
 
Exceptionhandelingin asp net
Exceptionhandelingin asp net
Arul Kumar
 
Chapter 7
Chapter 7
application developer
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
Knoldus Inc.
 
Exception handling
Exception handling
Iblesoft
 
Exception guidelines in c#
Exception guidelines in c#
Ahmed Helmy
 
Exceptions overview
Exceptions overview
Bharath K
 
Chapter 9
Chapter 9
application developer
 
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
NALANDACSCCENTRE
 
Introduction of exception in vb.net
Introduction of exception in vb.net
suraj pandey
 
Exceptions
Exceptions
DeepikaT13
 
Error handling in ASP.NET
Error handling in ASP.NET
baabtra.com - No. 1 supplier of quality freshers
 
Design byexceptions
Design byexceptions
Asif Tasleem
 
Exception handling
Exception handling
Ravi Sharda
 
Exceptions
Exceptions
motthu18
 
Exception Handling_ Mastering the Art of Dealing with Errors and Exceptions.pdf
Exception Handling_ Mastering the Art of Dealing with Errors and Exceptions.pdf
RamirezCarl
 
41c
41c
Sireesh K
 
Exception handling in ASP .NET
Exception handling in ASP .NET
baabtra.com - No. 1 supplier of quality freshers
 
12. Exception Handling
12. Exception Handling
Intro C# Book
 
Ad

More from Randy Connolly (20)

Celebrating the Release of Computing Careers and Disciplines
Celebrating the Release of Computing Careers and Disciplines
Randy Connolly
 
Public Computing Intellectuals in the Age of AI Crisis
Public Computing Intellectuals in the Age of AI Crisis
Randy Connolly
 
Why Computing Belongs Within the Social Sciences
Why Computing Belongs Within the Social Sciences
Randy Connolly
 
Ten-Year Anniversary of our CIS Degree
Ten-Year Anniversary of our CIS Degree
Randy Connolly
 
Careers in Computing (2019 Edition)
Careers in Computing (2019 Edition)
Randy Connolly
 
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Randy Connolly
 
Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)
Randy Connolly
 
Modern Web Development (2018)
Modern Web Development (2018)
Randy Connolly
 
Helping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing Disciplines
Randy Connolly
 
Constructing a Web Development Textbook
Constructing a Web Development Textbook
Randy Connolly
 
Web Development for Managers
Web Development for Managers
Randy Connolly
 
Disrupting the Discourse of the "Digital Disruption of _____"
Disrupting the Discourse of the "Digital Disruption of _____"
Randy Connolly
 
17 Ways to Fail Your Courses
17 Ways to Fail Your Courses
Randy Connolly
 
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Randy Connolly
 
Constructing and revising a web development textbook
Constructing and revising a web development textbook
Randy Connolly
 
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Randy Connolly
 
Citizenship: How do leaders in universities think about and experience citize...
Citizenship: How do leaders in universities think about and experience citize...
Randy Connolly
 
Thinking About Technology
Thinking About Technology
Randy Connolly
 
A longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission data
Randy Connolly
 
Web Security
Web Security
Randy Connolly
 
Celebrating the Release of Computing Careers and Disciplines
Celebrating the Release of Computing Careers and Disciplines
Randy Connolly
 
Public Computing Intellectuals in the Age of AI Crisis
Public Computing Intellectuals in the Age of AI Crisis
Randy Connolly
 
Why Computing Belongs Within the Social Sciences
Why Computing Belongs Within the Social Sciences
Randy Connolly
 
Ten-Year Anniversary of our CIS Degree
Ten-Year Anniversary of our CIS Degree
Randy Connolly
 
Careers in Computing (2019 Edition)
Careers in Computing (2019 Edition)
Randy Connolly
 
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Facing Backwards While Stumbling Forwards: The Future of Teaching Web Develop...
Randy Connolly
 
Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)
Randy Connolly
 
Modern Web Development (2018)
Modern Web Development (2018)
Randy Connolly
 
Helping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing Disciplines
Randy Connolly
 
Constructing a Web Development Textbook
Constructing a Web Development Textbook
Randy Connolly
 
Web Development for Managers
Web Development for Managers
Randy Connolly
 
Disrupting the Discourse of the "Digital Disruption of _____"
Disrupting the Discourse of the "Digital Disruption of _____"
Randy Connolly
 
17 Ways to Fail Your Courses
17 Ways to Fail Your Courses
Randy Connolly
 
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Red Fish Blue Fish: Reexamining Student Understanding of the Computing Discip...
Randy Connolly
 
Constructing and revising a web development textbook
Constructing and revising a web development textbook
Randy Connolly
 
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Computing is Not a Rock Band: Student Understanding of the Computing Disciplines
Randy Connolly
 
Citizenship: How do leaders in universities think about and experience citize...
Citizenship: How do leaders in universities think about and experience citize...
Randy Connolly
 
Thinking About Technology
Thinking About Technology
Randy Connolly
 
A longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission data
Randy Connolly
 

Recently uploaded (20)

cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
Curietech AI in action - Accelerate MuleSoft development
Curietech AI in action - Accelerate MuleSoft development
shyamraj55
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
2025_06_18 - OpenMetadata Community Meeting.pdf
2025_06_18 - OpenMetadata Community Meeting.pdf
OpenMetadata
 
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
WebdriverIO & JavaScript: The Perfect Duo for Web Automation
digitaljignect
 
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
Salesforce Summer '25 Release Frenchgathering.pptx.pdf
yosra Saidani
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Oh, the Possibilities - Balancing Innovation and Risk with Generative AI.pdf
Priyanka Aash
 
"Scaling in space and time with Temporal", Andriy Lupa.pdf
"Scaling in space and time with Temporal", Andriy Lupa.pdf
Fwdays
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
AI Agents and FME: A How-to Guide on Generating Synthetic Metadata
Safe Software
 
10 Key Challenges for AI within the EU Data Protection Framework.pdf
10 Key Challenges for AI within the EU Data Protection Framework.pdf
Priyanka Aash
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 

ASP.NET 05 - Exception Handling And Validation Controls

  • 1. Chapter 5 Exception Handling and Validation Controls No one is so brave that he is not perturbed by the unexpected. Julius Caesar, De Bello Gallico , 6.39.
  • 2. Overview Exception handling in C# Exception handling in ASP.NET Validation controls
  • 3. Error Handling Even the best written Web application can suffer from runtime errors. Most complex Web applications must interact with external systems such as databases, Web services, RSS feeds, email servers, file system, and other externalities that are beyond your control. A failure in any one of these systems means that your application can also no longer run successfully. It is vitally important that your applications can gracefully handle such problems.
  • 4. .NET Exception Handling When an error occurs, something called an exception is raised, or thrown in the nomenclature of .NET. When an error occurs, either the system or the currently executing application reports it by throwing an exception containing information about the error. When thrown, an exception can be handled by the application or by ASP.NET itself.
  • 5. Exception Handling Model In the .NET exception handling model, exceptions are represented as objects. The ancestor class for all exceptions is Exception . This class has many subclasses. Every Exception object contains information about the error.
  • 6. Default Error Page When an exception is raised but not handled by the application, ASP.NET displays the default error page . This page displays: the exception message the exception type the line that it occurred on stack trace
  • 8. Handling Exceptions Although this ASP.NET default error page is quite useful when developing and debugging an application, you might not always want to display this page when an exception occurs. Instead, you might want to handle the exception. There are three different ways or levels where you can do so: At the class level At the page level At the application level.
  • 9. Class level exception handling All .NET languages provide a mechanism for separating regular program code from exception handling code. In C#, this is accomplished via the try…catch block. If a runtime error occurs during the execution of any code placed within a try block, the program does not crash … … but instead tries to execute the code contained in one of the catch blocks.
  • 10. try…catch block try { double dVal1 = Convert.ToDouble(txtValue1.Text); double dVal2 = Convert.ToDouble(txtValue2.Text); double result = dVal1 / dVal2; labMessage.Text = txtValue1.Text + &quot;/&quot; + txtValue2.Text; labMessage.Text += &quot;=&quot; + result; } catch (FormatException ex1) { labMessage.Text = &quot;Please enter a valid number&quot;; } catch (Exception ex2) { labMessage.Text = &quot;Unable to compute a value with these values&quot;; }
  • 11. finally block There may be times when you want to execute some block of code regardless of whether an exception occurred. The classic example is closing a database connection no matter whether the SQL operation was successful or generated an exception. In such a case, you can use the optional finally block
  • 12. finally block try { // Open a database connection // Execute SQL statement } catch (DbException ex) { // Handle database exception } finally { // Close database connection if it exists }
  • 13. Cost of Exceptions Throwing exceptions is relatively expensive in terms of CPU cycles and resource usage. As a result, one should try to use exceptions to handle only exceptional situations. If your code relies on throwing an exception as part of its normal flow, you should refactor the code to avoid exceptions, perhaps by using a return code or some other similar mechanism instead.
  • 14. Using Exceptions try { SomeBusinessObject.Login(email); // Other code dependent upon a successful login } catch (Exception ex) { // Display message that email was not found } bool okay = SomeBusinessObject.Login(email); if (! okay) { // Display error message on page } else { // Other code dependent upon a successful login } bad good
  • 15. Exception Handling Strategies If you design your code so that exceptions are thrown only in truly exceptional situations, what do you when one of these exceptional exceptions occurs?
  • 16. Exception Handling Strategies Possible strategies: “ Swallow” the exception by catching and ignoring the exception by continuing normal execution. Almost never appropriate. Completely handle the exception within the catch block. Ignore the exception by not catching it (and thus let some other class handle it). Catch the exception and rethrow it for some other class to handle it.
  • 17. Exception Handling Strategies You may want to know when an exception occurs in a production application so that you can change the code to prevent it from occurring in the future. In this case, you might not want to catch the exception but instead let some other class “higher” in the calling stack handle it, perhaps by recording the exception to some type of exception log. Even if you are not recording an exception log, you should remember that in general, you should not catch exceptions in a method unless it can handle them, such as by: logging exception details, performing some type of page redirection, retrying the operation, performing some other sensible action.
  • 18. Page Level Exception Handling ASP.NET allows the developer to handle errors on a page basis via the page’s Page_Error event handler. The Page_Error event handler is called whenever an uncaught exception occurs during the exception of the page.
  • 19. Page_Error event handler public partial class PageExceptionTest : System.Web.UI.Page { … private void Page_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); Response.Write(&quot;<h1>An error has occurred</h1>&quot;); Response.Write(&quot;<h2>&quot; + ex.Message + &quot;</h2>&quot;); Response.Write(&quot;<pre>&quot; + ex.StackTrace + &quot;</pre>&quot;); Context.ClearError(); } }
  • 20. Application level exception handling There are two different ways that you can handle an exception at the application level: using a Application_Error event handler using the ASP.NET error page redirection mechanism.
  • 21. Using the Application_Error Handler ASP.NET allows the developer to handle errors on an application-wide basis via the Application_Error event handler. This handler resides in the application’s Global.asax file and is often the preferred location to handle uncaught exceptions in an application. Because you often want to do the same thing for all unhandled exceptions in your application. Rather than have the same type of error-logging code on every single page, it makes sense to centralize this code into a single spot.
  • 22. Custom Error Page To use a custom error page, you can change the settings of the <customErrors> element in the Web.config file. In this element, you can specify the custom page that is to be displayed. <system.web> <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; /> … </system.web>
  • 23. Custom Error Pages You can create custom error pages for different HTTP error codes. For example, a common feature of many Web sites is to provide custom HTTP 404 (requested page not found) and HTTP 500 (server error) error pages. You can specify custom pages for HTTP error codes within the <customErrors> element. <customErrors mode=&quot;On&quot; defaultRedirect=&quot;FriendlyErrorPage.aspx&quot; > <error statusCode=&quot;404&quot; redirect=&quot;custom404.aspx&quot; /> <error statusCode=&quot;500&quot; redirect=&quot;custom500.aspx&quot; /> </customErrors>
  • 24. Validation Server Controls These are a special type of Web server control. They significantly reduce some of the work involved in validating user data. They are used to validate or verify that certain input server controls (such as TextBox , RadioButtonList , or DropDownList ) contain correct data.
  • 25. Validation Server Controls RequiredFieldValidator Ensures that the input control is not empty. CompareValidator Compares a user entry against another value or control. RangeValidator Checks if a user entry is between a lower and upper boundary. RegularExpressionValidator Checks if a user entry matches a pattern defined by a regular expression CustomValidator Checks a user entry using custom validation logic. ValidationSummary Displays the error messages from all validation controls in a single location.
  • 26. Validation Server Controls You use validation server controls as you do other server controls. That is, you add the markup to your .aspx file where you would like an error indicator to be displayed (typically adjacent to the field it is validating). Each validation control references another input server control elsewhere on the page. <asp:TextBox ID=&quot;txtUserName&quot; runat=&quot;server&quot; /> <asp:RequiredFieldValidator Id=&quot;reqUser&quot; runat=&quot;server&quot; ControlToValidate=&quot;txtUserName&quot; Text=&quot;Please enter a User Name&quot; />
  • 27. Form Validation Process When a form that uses these validators is submitted, the user’s input is validated first by using Javascript on the client side if enabled and if supported by the browser. If there is an error, an error message is displayed without a round-trip to the server. If no error (or no Javascript or if client validation is disabled), the data is passed to the server and the data is checked once again on the server side. If the data is not valid, an error message is generated and ultimately sent back to the browser (along with all the other form data).
  • 28. Form Validation Process Why is both client-side and server-side data validation necessary? Client-side validation is useful because it reduces round-trips to the server. This provides immediate feedback to the user as well as improves server performance. Client-side validation by itself is not sufficient. The user could be using a browser that does not support scripting. that is, using an ancient browser or, more commonly, has scripting turned off via the browser preferences. Client-side scripting is also potentially vulnerable to “script exploits.”
  • 29. Form Validation Process User data must thus be validated on both the client and the server side. Validation controls automatically generate the Javascript necessary for client-side validation as well as perform, behind the scenes, the server-side validation.
  • 30. Validation Controls See pages 280-308