120 likes | 228 Views
Handling Ugly Page Crashes. With Try - Catch. Handling Ugly Page Crashes. Page crashes are ugly Syntactically correct code also fails TRY-CATCH helps recovery Use TRY-CATCH while developing web pages TRY contains the risky code CATCH contains recovery code
E N D
Handling Ugly Page Crashes With Try - Catch
Handling Ugly Page Crashes • Page crashes are ugly • Syntactically correct code also fails • TRY-CATCH helps recovery • Use TRY-CATCH while developing web pages • TRY contains the risky code • CATCH contains recovery code • FINALLY contains code that must always execute
What it looks like TRY to run this Try Catch (Exception Ex) Finally { there are lines of code here; That have some chance of crashing; } No Error? Run FINALLY anyway Error? Then CATCH it here Continue on Run Finally { List the error message; and any other recovery steps; } { What must always be run; Comes in these lines of code; }
The first checkbox Syntactically perfect pages also fail 1. Customer Registration page 3. First value is #0 4. The last value is #3 So the code loops 4 times The syntax is good. No 4th checkbox Logic fails. This is a RUNTIME error. 2. There are 3 checkboxes in the list
Page with error WITH TRY-CATCH 1. No ugly yellow screen with crazy stuff 2. Error message appears nicely 3. The page actually finishes running Results are in the box!
How to write a TRY-CATCH • Potentially risky code • It in a TRY block • It with a CATCH block just under it • Add a FINALLY block just under that SELECT SURROUND SUPPORT SOMETIMES
For example Try { // sample code here // that has potential to fail } Catch (Exception Ex) { // do this when the code above fails // say what the code in the try block was doing // and what (if you know) the error could be } Finally { // always do this stuff // such as closing readers, // or even connections if you are done with the database }
Circled code has been added ] This code could fail ] If it fails, then run this code to show what the error message is lblErrors.Text=Ex.Message.ToString();
Some places to use Try-Catch • Loops, especially where one hard codes counters • While converting between data types • While executing commands, either with DataReaders, or ExecuteNonQueries