Powered by Blogger.

The try-catch-finally statement in JavaScript

Introduction:-

Error handling is an important part of any software developers' job. The .NET Framework offers some very powerful tools to handle errors in a relatively easy manner. One of these tools is the Try-Catch- Finally statement. Yet in the few months that I have been programming, I have seen quite some (wrong) uses of the Try-Catch-Finally... not only by beginning progammers, but also by so-called seniors and gurus!

There are many books and articles discussing correct error handling in .NET, but many fail to give a simple yet complete overview of the so-important Try-Catch-Finally-block. With this article, I hope to inform any software developer about some proper and detailed uses of the Try-Catch-Finally-block.

Definition of try-catch-finally statement:-

The finally clause defines a block of code that always executes. If try block executes properly then catch block will not execute, and if try block will not execute properly then catch block will execute, but the finally block must executes.

try-catch-finally statement Example:-

 public class Test_finally{
   public static void main(String[]args){
     try {
         int i=9/0;
         System.out.println(i);
     }catch(ArithmeticException e1){
        System.out.println(”Arithmetic Exception.” +e1);
     }finally{
        System.out.println(”finally block must executes”);
     }
   }
 }


The Exception Declare Rules

In Java, we can declare exceptions by following:

1. try−catch−finally
2. void methodA() throws IOException {}
3. void methodB() throws IOException, OtherException {}


 public class Declar eException{
   public void methodA(){
     try{
     }catch(Exception e){
        System.out.println(”If error in try then catch execut e”);
     }finally{
        System.out.println(”finally must executes”);
     }
   }
   public void methodB() throws SecurityException{
  }
   public void methodC() throws SecurityException, Exception{
   }
 }

A Simple Try- Catch-Finally:-

Let's move on to the second button on the form. Click it and notice that your cursor turns into a waiting cursor! Unfortunately after a few seconds, all goes wrong.

Private Sub btnSimpleTryCatchFinally_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnSimpleTryCatchFinally.Click
        ' The cursor goes into waiting mode.
        Me.Cursor = Cursors.WaitCursor
        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
    End Sub

This piece of code looks very much like that of the previous button, with the exception that this is a long process and we turn the cursor into a wait cursor. I have often waited a long time for applications that appeared to be loading, but had actually crashed which caused my cursor to always stay in waiting mode! So how do we make sure the cursor in OUR application always turns back to default? Easy, we use a Finally... block. The Finally... statement in a Try... Catch... Finally... block is ALWAYS executed. So if everything would go as it should, my code would be executed, it would skip the Catch block, go into my Finally block and put my cursor back to normal. If an Exception occurs (like here), the code jumps into the Catch block, handles the error and then goes into my Finally block, making sure that my cursor is turned back to normal. Notice how I initially change my cursor outside of the Try... Catch... Finally... block. This makes sure that when I go into my Finally, my cursor is actually a wait cursor. In this example, it would not matter if the first line of code is inside or outside the Try... Catch... Finally... block. But it will matter later on as you will see. I should also mention that the Try... Finally... block can also be used without the Catch. We will see an example of that later on.

Nested Try-Catch-Finally:-

Sometimes, you want to do multiple error handlings in one block of code. In this case, it is possible to use nested Try-Catch-Finally.... blocks.

Private Sub btnNestedTryCatch_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnNestedTryCatch.Click
        Try
            ' Some code here...
            Try
                ' Some more code here...
                Dim table As New DataTable
                Try
                    ' Some more code here...
                    ' Oops! An error occurs!
                    Throw New System.Exception("I come from the third nested try.")
                    ' No Catch here, only a finally.
                Finally
                    ' This code will always execute.
                    table.Dispose()
                End Try
            Catch ex As Exception
                MessageBox.Show(ex.Message & Environment.NewLine & _
        " I was handled in the second Try... Catch... block.", _
                                Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        Catch ex As Exception
            MessageBox.Show(ex.Message & Environment.NewLine & _
        " I was handled in the first Try... Catch... block.", _
                            Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

In this example, there are three nested Try... blocks. The third one has no Catch, but a Finally only. This is no problem though, because if an Exception occurs here, it will simply be thrown to the second Try... block which does have a Catch that handles the Exception.

If an Exception occurs in the second or third nested Try... block, the Exception will never reach the first Try... block (unless it is rethrown). If the Exception occurs in the first block, it will never reach the second and third Try... blocks.

The Finally... will only be executed if your code makes it to the third Try... block. Of course you can also add Finally... blocks in the first and second Try... blocks and you can also add multiple Catches (for SqlException, IOException, etc.).

Also note that I have two variables named ex. This means that the ex variable only exists within the Catch block. Also, I declare the DataTable in the second nested Try... block which means it does not exist in the first Try... block, making it impossible to Dispose it in a Finally... block in the first Try... statement.


Nested try/catch/finally statements:-

As a reminder, try should never be defined just by itself, but always followed by either catch, finally, or both. Within each clause, you can define additional try/catch/finally statements following the same aforementioned rule. Take the instance where an error has occurred within the catch clause- defining an additional try/catch statement inside it takes care of it:

var ajaxrequest=null
if (window.ActiveXObject){ //Test for support for different versions of ActiveXObject in IE
 try {
  ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP")
 }
 catch (e){
  try{
   ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP")
  } //end inner try
  catch (e){
   alert("I give up. Your IE doesn't support Ajax!")
  } //end inner catch
 } //end outer catch
}
else if (window.XMLHttpRequest) // if Mozilla, Safari etc
 ajaxrequest=new XMLHttpRequest()

ajaxrequest.open('GET', 'process.php', true) //do something with request


Handling runtime errors in JavaScript using try/catch/finally:

Error handling, like many aspects of JavaScript, has been maturing since the dark ages of Netscape and IE4. No longer are you forced to settle for what the browser throws in your face in an event of a JavaScript error, but instead can take the matter into your own hands. The try/catch/finally statement of JavaScript lets you dip your toes into error prune territory and "reroute" when a JavaScript "exception" is encountered. Along with other defensive coding techniques such as Object detection and the onError event, try/catch/finally adds the ability to navigate around certain errors that in the past would have instantly stopped your script at its tracks. No more!
try/catch/finally

try/catch/finally are so called exception handling statements in JavaScript. An exception is an error that occurs at runtime due to an illegal operation during execution. Examples of exceptions include trying to reference an undefined variable, or calling a non existent method. This versus syntax errors, which are errors that occur when there is a problem with your JavaScript syntax. Consider the following examples of syntax errors versus exceptions:

    alert("I am missing a closing parenthesis //syntax error
    alert(x) //exception assuming "x" isn't defined yet
    undefinedfunction() //exception

try/catch/finally lets you deal with exceptions gracefully. It does not catch syntax errors, however (for those, you need to use the onerror event). Normally whenever the browser runs into an exception somewhere in a JavaScript code, it displays an error message to the user while aborting the execution of the remaining code. You can put a lid on this behaviour and handle the error the way you see fit using try/catch/finally. At its simplest you'd just use try/catch to try and run some code, and in the event of any exceptions, suppress them:

try{
 undefinedfunction()
}
catch(e){
 //catch and just suppress error
}

Assuming undefinedfunction() is undefined, when the browser runs the above, no errors will be shown. The syntax for try/catch/finally is a try clause followed by either a catch or finally clause (at least one or both of them). The catch clause if defined traps any errors that has occurred from try, and is indirectly passed the error object that contains additional info about the error. Lets see a slightly more complex example now:

try{
 undefinedfunction()
 alert('I guess you do exist')
}
catch(e){
 alert('An error has occurred: '+e.message)
}

Here I'm using a nested try/catch statement to try and determine in IE which version of the ActiveX Object it supports that's needed to initialize an Ajax request. Using object detection won't work here, since the issue isn't whether the browser supports ActiveXObject here, but which version.

2 comments:

  1. This is one awesome blog article. Much thanks again.
    I really enjoy the blog.Much thanks again. Really Great.


    oracle online training
    sap fico online training
    dotnet online training
    qa-qtp-software-testing-training-tutorial

    ReplyDelete
  2. Pretty good post. I just came across your site and wanted to say that I’ve really enjoyed reading your posts. In any case I’ll be subscribing to your feed and I hope you will keep a good work!Cheer!

    sap online training
    software online training
    sap sd online training
    hadoop online training
    sap-crm-online-training

    ReplyDelete