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

More Related Content

What's hot (20)

Partitioning
PartitioningPartitioning
Partitioning
Reema Gajjar
 
Oracle: Procedures
Oracle: ProceduresOracle: Procedures
Oracle: Procedures
DataminingTools Inc
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
OXUS 20
 
Threads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptxThreads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptx
azkamurat
 
Java Notes
Java Notes Java Notes
Java Notes
Sreedhar Chowdam
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
Nilesh Dalvi
 
Hadoop And Their Ecosystem ppt
 Hadoop And Their Ecosystem ppt Hadoop And Their Ecosystem ppt
Hadoop And Their Ecosystem ppt
sunera pathan
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL DatabasePerformance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
introduction and configuration of IIS (in addition with printer)
introduction and configuration of IIS (in addition with printer)introduction and configuration of IIS (in addition with printer)
introduction and configuration of IIS (in addition with printer)
Assay Khan
 
Stored procedure
Stored procedureStored procedure
Stored procedure
baabtra.com - No. 1 supplier of quality freshers
 
SQL Constraints
SQL ConstraintsSQL Constraints
SQL Constraints
Randy Riness @ South Puget Sound Community College
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
DevAdnani
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
shanmukhareddy dasi
 
Assemblies
AssembliesAssemblies
Assemblies
Janas Khan
 
Relational databases
Relational databasesRelational databases
Relational databases
Fiddy Prasetiya
 
Introduction to Database
Introduction to DatabaseIntroduction to Database
Introduction to Database
Syed Zaid Irshad
 
Practical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresPractical Partitioning in Production with Postgres
Practical Partitioning in Production with Postgres
EDB
 
1.2 steps and functionalities
1.2 steps and functionalities1.2 steps and functionalities
1.2 steps and functionalities
Krish_ver2
 
Redo log
Redo logRedo log
Redo log
PaweOlchawa1
 
Fundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and AnswersFundamentals of Database Systems Questions and Answers
Fundamentals of Database Systems Questions and Answers
OXUS 20
 
Threads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptxThreads and synchronization in C# visual programming.pptx
Threads and synchronization in C# visual programming.pptx
azkamurat
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
Nilesh Dalvi
 
Hadoop And Their Ecosystem ppt
 Hadoop And Their Ecosystem ppt Hadoop And Their Ecosystem ppt
Hadoop And Their Ecosystem ppt
sunera pathan
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL DatabasePerformance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
introduction and configuration of IIS (in addition with printer)
introduction and configuration of IIS (in addition with printer)introduction and configuration of IIS (in addition with printer)
introduction and configuration of IIS (in addition with printer)
Assay Khan
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
DevAdnani
 
Practical Partitioning in Production with Postgres
Practical Partitioning in Production with PostgresPractical Partitioning in Production with Postgres
Practical Partitioning in Production with Postgres
EDB
 
1.2 steps and functionalities
1.2 steps and functionalities1.2 steps and functionalities
1.2 steps and functionalities
Krish_ver2
 

Viewers also liked (8)

ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828
Viral Patel
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
LearningTech
 
461
461461
461
Jesus Valenzuela
 
Exception
ExceptionException
Exception
abhay singh
 
Interfaces & Packages V2
Interfaces & Packages V2Interfaces & Packages V2
Interfaces & Packages V2
Dr Anjan Krishnamurthy
 
Servlets lecture2
Servlets lecture2Servlets lecture2
Servlets lecture2
Tata Consultancy Services
 
Data Validation Victories: Tips for Better Data Quality
Data Validation Victories: Tips for Better Data QualityData 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 WorkTEDx Manchester: AI & The Future of Work
TEDx Manchester: AI & The Future of Work
Volker Hirsch
 
ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828ASP.NET User Controls - 20090828
ASP.NET User Controls - 20090828
Viral Patel
 
Exception handling in asp.net
Exception handling in asp.netException 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 QualityData 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 WorkTEDx 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)

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
Ketan Raval
 
Exception handling
Exception handlingException handling
Exception handling
Mahesh Pachbhai
 
Php exceptions
Php exceptionsPhp exceptions
Php exceptions
Damian Sromek
 
PHP Exception handler
PHP Exception handlerPHP Exception handler
PHP Exception handler
Ravi Raj
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
Ben Abdallah Helmi
 
$Cash
$Cash$Cash
$Cash
ErandaMoney
 
$Cash
$Cash$Cash
$Cash
ErandaMoney
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
Angelin R
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
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
Akhil Mittal
 
Javascript
JavascriptJavascript
Javascript
Nagarajan
 
London SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error HandlingLondon SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error Handling
Richard Clark
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
Chris x-MS
 
Error management
Error managementError management
Error management
daniil3
 
Lightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesLightning page optimization &amp; best practices
Lightning page optimization &amp; best practices
Gaurav Jain
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
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
Ketan Raval
 
PHP Exception handler
PHP Exception handlerPHP Exception handler
PHP Exception handler
Ravi Raj
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5SCWCD : Handling exceptions : CHAP : 5
SCWCD : Handling exceptions : CHAP : 5
Ben Abdallah Helmi
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
Angelin R
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
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
Akhil Mittal
 
London SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error HandlingLondon SF Developers: Custom Lightning Component Error Handling
London SF Developers: Custom Lightning Component Error Handling
Richard Clark
 
Web Application Security
Web Application SecurityWeb Application Security
Web Application Security
Chris x-MS
 
Error management
Error managementError management
Error management
daniil3
 
Lightning page optimization &amp; best practices
Lightning page optimization &amp; best practicesLightning page optimization &amp; best practices
Lightning page optimization &amp; best practices
Gaurav Jain
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Ad

More from Randy Connolly (20)

Celebrating the Release of Computing Careers and Disciplines
Celebrating the Release of Computing Careers and DisciplinesCelebrating 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 CrisisPublic 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 SciencesWhy 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 DegreeTen-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)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...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)Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)
Randy Connolly
 
Modern Web Development (2018)
Modern Web Development (2018)Modern Web Development (2018)
Modern Web Development (2018)
Randy Connolly
 
Helping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing DisciplinesHelping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing Disciplines
Randy Connolly
 
Constructing a Web Development Textbook
Constructing a Web Development TextbookConstructing a Web Development Textbook
Constructing a Web Development Textbook
Randy Connolly
 
Web Development for Managers
Web Development for ManagersWeb 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 _____"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 Courses17 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...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 textbookConstructing 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 DisciplinesComputing 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...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 TechnologyThinking About Technology
Thinking About Technology
Randy Connolly
 
A longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission dataA longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission data
Randy Connolly
 
Web Security
Web SecurityWeb Security
Web Security
Randy Connolly
 
Celebrating the Release of Computing Careers and Disciplines
Celebrating the Release of Computing Careers and DisciplinesCelebrating 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 CrisisPublic 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 SciencesWhy 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 DegreeTen-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)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...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)Where is the Internet? (2019 Edition)
Where is the Internet? (2019 Edition)
Randy Connolly
 
Modern Web Development (2018)
Modern Web Development (2018)Modern Web Development (2018)
Modern Web Development (2018)
Randy Connolly
 
Helping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing DisciplinesHelping Prospective Students Understand the Computing Disciplines
Helping Prospective Students Understand the Computing Disciplines
Randy Connolly
 
Constructing a Web Development Textbook
Constructing a Web Development TextbookConstructing a Web Development Textbook
Constructing a Web Development Textbook
Randy Connolly
 
Web Development for Managers
Web Development for ManagersWeb 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 _____"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 Courses17 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...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 textbookConstructing 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 DisciplinesComputing 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...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 TechnologyThinking About Technology
Thinking About Technology
Randy Connolly
 
A longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission dataA longitudinal examination of SIGITE conference submission data
A longitudinal examination of SIGITE conference submission data
Randy Connolly
 

Recently uploaded (20)

Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Agentic AI - The New Era of Intelligence
Agentic AI - The New Era of IntelligenceAgentic AI - The New Era of Intelligence
Agentic AI - The New Era of Intelligence
Muzammil Shah
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Cyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptxCyber Security Legal Framework in Nepal.pptx
Cyber Security Legal Framework in Nepal.pptx
Ghimire B.R.
 
Jira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : IntroductionJira Administration Training – Day 1 : Introduction
Jira Administration Training – Day 1 : Introduction
Ravi Teja
 
Palo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity FoundationPalo Alto Networks Cybersecurity Foundation
Palo Alto Networks Cybersecurity Foundation
VICTOR MAESTRE RAMIREZ
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 ADr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr Jimmy Schwarzkopf presentation on the SUMMIT 2025 A
Dr. Jimmy Schwarzkopf
 
SDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhereSDG 9000 Series: Unleashing multigigabit everywhere
SDG 9000 Series: Unleashing multigigabit everywhere
Adtran
 
Supercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMsSupercharge Your AI Development with Local LLMs
Supercharge Your AI Development with Local LLMs
Francesco Corti
 
Co-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using ProvenanceCo-Constructing Explanations for AI Systems using Provenance
Co-Constructing Explanations for AI Systems using Provenance
Paul Groth
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...Cyber security cyber security cyber security cyber security cyber security cy...
Cyber security cyber security cyber security cyber security cyber security cy...
pranavbodhak
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
GDG Cloud Southlake #43: Tommy Todd: The Quantum Apocalypse: A Looming Threat...
James Anderson
 
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure ModesCognitive Chasms - A Typology of GenAI Failure Failure Modes
Cognitive Chasms - A Typology of GenAI Failure Failure Modes
Dr. Tathagat Varma
 
Agentic AI - The New Era of Intelligence
Agentic AI - The New Era of IntelligenceAgentic AI - The New Era of Intelligence
Agentic AI - The New Era of Intelligence
Muzammil Shah
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 

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