Hi guys. How are you today? I wolud like to ask what are these try catch and finally statements in JS. I read it all on w3school and MDN but still can't grasp everything. I understand vaguely that you use them to run test but ... that's it. Can you help me? Thank you in advance. Cheers Dani
Sometimes there are things that are outside of your control and you can't control all the different risk factors. Try/Catch lets you have a go but have something in place for when it fails. This is a PHP example but the concept remains the same. I was sending email addresses to a mail handler. Some of the emails were invalid and the mail handler hadn't been coded to degrade elegantly so I was getting fatal errors. I was able to code for some of those errors like commas instead of fullstops and spaces but others were just too invalid. So I put a try around the mail command and when there is an error the catch code will email the local administrator and ask them to find out the right email and update the record. And then there's this anecdote from my mainframe days. I was sent to Boston to work with some consultants who were clipping the ticket big time but adding little to the project. Near the end of my time with them one of them asked me when we were going to add in the error handling. Because we had 100% control over the data and had written robust code we didn't need any more error handling than had been written in prior to delivery. Adding it after the fact would have been an unnecessary overhead.
@sarahk - I really appreciate the examplesyou have presented but i couldn't get them well. So it is something like if ( ) {do this;} else {do sth else;} like a weird if/else statement? The idea is to have a back up plan so that if sth goes wrong you can place an alternative. Is it often used? Can you show me some examples and include the throw and finally. Thank you guys
Dani, this is something called exception handling in JS. Simply, These statement are used to remove some predefined error conditions These are very easy to use put your JS code segment into try{} block where an error may be present at run time. Put some code to run for recovery from error in catch{} block and if you want some code must be run even after a error statement you can write that code segment into finally block. For Example: Try ' Some code here... ' This is some heavy code! Threading.Thread.Sleep(5000) ' Oops! An error occurs! Throw New System.Exception("An unexpected error occurred.") ' Some more code here... Catch ex As Exception ' Handle the exception. MessageBox.Show(ex.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error) Finally ' Make sure the cursor is set back to default! Me.Cursor = Cursors.Default End Try