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.

Java - Call Stack Mechanism in JavaScript

Call Stack:-

Most modern implementations use a call stack, a special case of the stack data structure, to implement subroutine calls and returns. Each procedure call creates a new entry, called a stack frame, at the top of the stack; when the procedure returns, its stack frame is deleted from the stack, and its space may be used for other procedure calls. Each stack frame contains the private data of the corresponding call, which typically includes the procedure's parameters and internal variables, and the return address.

The call sequence can be implemented by a sequence of ordinary instructions (an approach still used in reduced instruction set computing (RISC) and very long instruction word (VLIW) architectures), but many traditional machines designed since the late 1960s have included special instructions for that purpose.

The call stack is usually implemented as a contiguous area of memory. It is an arbitrary design choice whether the bottom of the stack is the lowest or highest address within this area, so that the stack may grow forwards or backwards in memory; however, many architectures chose the latter.[citation needed]

Some designs, notably some Forth implementations, used two separate stacks, one mainly for control information (like return addresses and loop counters) and the other for data. The former was, or worked like, a call stack and was only indirectly accessible to the programmer through other language constructs while the latter was more directly accessible.

When stack-based procedure calls were first introduced, an important motivation was to save precious memory.[citation needed] With this scheme, the compiler does not have to reserve separate space in memory for the private data (parameters, return address, and local variables) of each procedure. At any moment, the stack contains only the private data of the calls that are currently active (namely, which have been called but haven't returned yet). Because of the ways in which programs were usually assembled from libraries, it was (and still is) not uncommon to find programs that include thousands of subroutines, of which only a handful are active at any given moment.[citation needed] For such programs, the call stack mechanism could save significant amounts of memory. Indeed, the call stack mechanism can be viewed as the earliest and simplest method for automatic memory management.

However, another advantage of the call stack method is that it allows recursive subroutine calls, since each nested call to the same procedure gets a separate instance of its private data.

Call Stack Mechanism:-

If a statement throws an exception, and that exception is not handled in the immediately enclosing method, then that exception is throws to the calling method. If the exception is not handled in the calling method, it is thrown to the caller of that method. This process continues. If the exception is still not handled by the time it gets back to the main() method and main() does not handle it, the exception terminates the program abnormally.

Single-Threaded Stack Mechanism Extensions:-

This section discusses call stack mechanisms that are relatively trivial modifications of the traditional single-threaded call stack mechanism. All maintain each thread's call stack as a contiguous region of memory. Solaris [22] uses a multi-threaded call stack mechanism that is practically the standard for modern operating systems. Each thread has its own stack space reserved near the top of virtual address space. The size of the call stack can be set to a custom value during thread creation. If no stack space size is specified, a large value (typically 2MB) will be used instead. Stack overflow is detected via the use of a "red zone", which refers to the process of appending a page of memory without read or write permissions to the end of a thread's stack space. This page will causes a memory fault if accessed.

Oberon with active objects [12] can be viewed as a subset of the above call stack mechanism specifically tailored to support a large number of small call stacks. It does this by reserving the upper 2GB of virtual address space for small call stacks that are each a maximum of 128KBytes, thereby supporting up to 16,384 call stacks simultaneously. Concurrent Oberon [18] uses a call stack that is a fixed size determined at thread creation, but allocated on the heap. Overflow is detected before it occurs via a check at the start of every procedure, and results in termination of the offending thread. While this method increases runtime overhead, it has the advantage of working on systems that do not have an MMU. The call stack is garbage collected once the thread terminates.

US patent 7,477,829 [27] attempts to address both heap contention and stack space in its proposed memory layout, depicted in Figure 2.4. Each stack/heap block is created from an initial base address, from which the thread and heap stack grow in opposite directions. Unfortunately, the patent does not specify how the initial base addresses are computed, but from Figure 2.4 it can be inferred that the base addresses are intended to be spaced apart evenly. Doing so would require knowledge of the maximum number of threads that the program would execute at one time. Stack and heap overflow are detected via the use of "dead zones"  that are "... impossible to read from or to write to... In so doing there is no chance of memory corruption between any of these thread heap/thread stack combinations" [27]. While the patent does not go into further details, it is inferred that these dead zones operate similarly to Solaris's red zones [22] by generating a page fault or similar hardware interrupt upon access.

All of the above methods suffer from the limitation that stack space for one thread cannot be shared with another, and each thread's stack space must always be large enough to handle the worst case stack usage, or the program will terminate with an error. This can lead to the situation where a program can prematurely "run out" of stack space due to a single thread exceeding its allotted stack space, even if there is plenty of unused stack space preallocated to other threads. These conditions also force a trade-off between the maximum allowable stack space per thread and the number of threads that can exist in a system at one time, which seems to run counter to the spirit of resource-sharing mechanics that govern system memory and hard disk space.

It is my opinion that this trade-off is a vestige of the success of the MMU (which gives the most assistance to processes that do not share address space) combined with the fact that a single-threaded program only requires a single call stack.

Multi-Threading's Call Stack Problems:-

Before examining the problems that multi-threading introduces, it is a good idea to first examine why the traditional call stack mechanism works so well for singlethreaded processes. Two important facts form the basis of its success:

• The MMU allows each process to use the entire address space as if it were the only process running on the system. Physical memory is not reserved for the process until it actually uses the space.

• For any single-threaded program, there is only one call stack required. As such, the operating system can, by default, reserve a stack so large that it is usually safe to assume that a properly-functioning program will not exhaust it. Reserving such a large portion of memory does not cause any negative effects because:

• Virtual address space will not map to physical memory until the program actually uses the virtual address space.

• The operating system automatically maps the used virtual address regions to physical memory that will not conflict with other processes. Multi-threading significantly changes the rules. A multi-threaded program requires one call stack per thread, all of which must exist within the same address space. This means that the MMU cannot help with multiple threads as it does with multiple processes. Most modern operating systems just create one "large" call stack for each thread at the top of virtual address space. However, when there are a large number of threads, this will cause the process to run out of virtual address space before it is actually out of memory. Shrinking each process's stack space until each thread's stack can fit may lead to one thread running out of stack space when there is otherwise lots of unused stack space remaining, This is especially likely to happen if thread stack usage patterns differ (e.g. one thread makes heavy use of recursion). It is possible to manually set stack space on a threadby- thread basis (e.g. giving a heavy stack space using thread more stack space).

However, this both increases the burden on the programmer and decreases the flexibility of the program (threads are locked into roles, not all threads have the ability to temporarily use a large amount of stack space). This harkens back to the days before the MMU when programmers used to manually give each process a certain Before examining the problems that multi-threading introduces, it is a good idea to first examine why the traditional call stack mechanism works so well for singlethreaded processes. Two important facts form the basis of its success:

• The MMU allows each process to use the entire address space as if it were the only process running on the system. Physical memory is not reserved for the process until it actually uses the space.

• For any single-threaded program, there is only one call stack required. As such, the operating system can, by default, reserve a stack so large that it is usually safe to assume that a properly-functioning program will not exhaust it. Reserving such a large portion of memory does not cause any negative effects because:

• Virtual address space will not map to physical memory until the program actually uses the virtual address space.

• The operating system automatically maps the used virtual address regions to physical memory that will not conflict with other processes. Multi-threading significantly changes the rules. A multi-threaded program requires one call stack per thread, all of which must exist within the same address space. This means that the MMU cannot help with multiple threads as it does with multiple processes. Most modern operating systems just create one "large" call stack for each thread at the top of virtual address space. However, when there are a large number of threads, this will cause the process to run out of virtual address space before it is actually out of memory. Shrinking each process's stack space until each thread's stack can fit may lead to one thread running out of stack space when there is otherwise lots of unused stack space remaining, This is especially likely to happen if thread stack usage patterns differ (e.g. one thread makes heavy use of recursion). It is possible to manually set stack space on a threadby- thread basis (e.g. giving a heavy stack space using thread more stack space).

However, this both increases the burden on the programmer and decreases the flexibility of the program (threads are locked into roles, not all threads have the ability to temporarily use a large amount of stack space). This harkens back to the days before the MMU when programmers used to manually give each process a certain With the number of cores on chips increasing, parallelism being touted as the way to increase performance in the future [23, 6, 10], and current operating system stack mechanics being bottleneck for the number of threads a process can run, it is clear that the lowly call stack is in need of investigation.

Multiple "catch" Clauses in JavaScript | Java

Introduction:-

The code bound by the try block need not always throw a single exception. If in a try block multiple and varied exceptions are thrown, then you can place multiple catch blocks for the same try block in order to handle all those exceptions. When an exception is thrown it traverses through the catch blocks one by one until a matching catch block is found. The program structure in such a case is:

Java Code:-

try
{
    // statements with multiple and varied exceptions
}
catch (<exception_one> obj)
{
    // statements to handle the exception
}
catch (<exception_two> obj)
{
    // statements to handle the exception
}
catch (<exception_three> obj)
{
    // statements to handle the exception
}

 Let us consider an example in which we are using two catch clauses catching the exception ArrayIndexOutOfBoundsException and ArithmeticException. In the first example a deliberate attempt has been made to store the value in the array beyond it’s upper limit thus causing the program to throw the exception ArrayIndexOutOfBoundsException, and to go to the first catch block. In the next example this error is rectified and the program is run again. A new error comes up which is the zero divide. Now this time the second catch block handles the error, and the first catch block is skipped.


Multiple Catch Clauses:-

In Java , there can be multiple catch blocks after a try block, and each catch block handing a different exception type.

Using Multiple catch Clauses Example:

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

Handling Multiple Catch Clauses:-

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.

The syntax for using this clause is given below:-

try{
???
???
}
catch(<exceptionclass_1> <obj1>){
//statements to handle the exception 
}

catch(<exceptionclass_2> <obj2>){
//statements to handle the exception 
}
catch(<exceptionclass_N> <objN>){
//statements to handle the exception 
}

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level.

Lets see an example given below which shows the implementation of multiple catch blocks for a single try block.

public class Multi_Catch
{
   public static void main (String args[])
   {
  int array[]={20,10,30};
  int num1=15,num2=0;
  int res=0;

  try
  {
   res = num1/num2;
  System.out.println("The result is" +res);

  for(int ct =2;ct >=0; ct--)
  {
   System.out.println("The value of array are" +array[ct]);
   }

  }

  catch (ArrayIndexOutOfBoundsException e)
   {
   System.out.println("Error?. Array is out of Bounds");
  }

   catch (ArithmeticException e)
   {
   System.out.println ("Can't be divided by Zero");
   }
   }
  }

Output of the program:

C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Can't be divided by Zero

So far we have seen how to use a single catch block, now we will see how to use more than one catch blocks in a single try block.In java when we handle the exceptions then we can have multiple catch blocks for a particular try block to handle many different kind of exceptions that may be generated while running the program i.e. you can use more than one catch clause in a single try block however every catch block can handle only one type of exception. this mechanism is necessary when the try block has statement that raise  different type of exceptions.

The syntax for using this clause is given below:-

try{
???
???
}
catch(<exceptionclass_1> <obj1>){
//statements to handle the exception 
}

catch(<exceptionclass_2> <obj2>){
//statements to handle the exception 
}
catch(<exceptionclass_N> <objN>){
//statements to handle the exception 
}

When an exception is thrown, normal execution is suspended. The runtime system proceeds to find a matching catch block that can handle the exception. If no handler is found, then the exception is dealt with by the default exception handler at the top level.

 Lets see an example given below which shows the implementation of multiple catch blocks for a single try block.

 public class Multi_Catch
{
   public static void main (String args[])
   {
  int array[]={20,10,30};
  int num1=15,num2=0;
  int res=0;

  try
  {
   res = num1/num2;
  System.out.println("The result is" +res);

  for(int ct =2;ct >=0; ct--)
  {
   System.out.println("The value of array are" +array[ct]);
   }

  }

  catch (ArrayIndexOutOfBoundsException e)
   {
   System.out.println("Error?. Array is out of Bounds");
  }

   catch (ArithmeticException e)
   {
   System.out.println ("Can't be divided by Zero");
   }
  }
  }
Output of the program:

C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Can't be divided by Zero

In this example we have used two catch clause catching the exception Array Index Out of Bounds Exception and Arithmetic Exception in which the statements that may raise exception are kept under the try block. When the program is executed, an exception will be raised. Now that time  the first catch block is skipped and the second catch block handles the error.

Like this Program:-

Lets have an another output, in which the second catch block is skipped and the first catch block handles the error.

public class Multi_Catch1
{
   public static void main (String args[])
   {
  int array[]=new int [5];
  int num1=15,num2=2;
  int res=0;

  try
  {
   res = num1/num2;
  System.out.println("The result is" +res);

  for(int ct =0;ct <=5; ct++)
  {
   array[ct] = ct * ct ;
   }

  }

  catch (ArrayIndexOutOfBoundsException e)
   {
   System.out.println("Assigning the array beyond the upper bound");
  }

   catch (ArithmeticException e)
   {
   System.out.println ("Can't be divided by Zero");
   }
  }
 }

Output of the Program:

C:\Roseindia\>javac Multi_Catch.java

C:\Roseindia\>java Multi_Catch

Assigning the array beyond the upper bound

Like this Example:-

Handling the Unreachable Code Problem The multiple catch blocks can generate unreachable code error i.e. if the first catch block contains the Exception class object then the subsequent catch blocks are never executed.  This is known as Unreachable code problem. To avoid this, the last catch block in multiple catch blocks must contain the generic class object that is called the Exception class. This exception class being the super class of all the exception classes and is capable of  catching any  types of exception. The generic Exception class can also be used with multiple catch blocks.

Take a look at the following example:

public class Generic_Excep
{
   public static void main (String args[])
  {
   String str = "Exception" ;
   int len=0;
   try
  {
   StringBuffer sbuf = new StringBuffer(str);
  len = str.length() ;
   for(int ct=len;ct>=0;ct--)
  {
  System.out.print(sbuf.charAt(ct));
   }
   }
   catch(Exception e)
  {
  System.out.println("Error...."+e);
   }
  }
 }

Output of the Program:

C:\Roseindia\>javac Generic_Excep.java

C:\Roseindia\>java Generic_Excep

Error....java.lang.StringIndexOutOfBoundsException: String index out of range: 9

In this example we didn't specify that which one exception may occur during the execution of program but here we are trying to access the value of an array that is out of bound still we don't need to worry about handle the exception because we have used the Exception class that is responsible to handle any type of exception.

Related Tags for Handling Multiple Catch Clauses:

java, c, exception,diff, io, multiple, type, ip, lock, block, handle, if, for, program, while, to, ram, run, single, exceptions, locks, generate, e, il, blocks, multi, can, use, ul, pe,  man, art, ce, in, part, different, m, nt, par, tr, clause, ca, j, cl, catch, running, icu, loc, how, pro, rate, cat, when, try, s, tip, at, any, k, ha, except, and, ar, rt, va, s, s, ren, th, av, hat, fe, many, ipl, ple, pl, pr, nd, only, on, ogr, o, nl

Java Program | Excellent example of The try-catch Statement in JavaScript

The Try-Catch Statement:-

To avoid the problem of code 3-20, we can use the try-catch statement. If any exception or error occurred in the try block then the catch block will execute. If try block execute without any error, then catch block will not execute.

Basic Syntax and Definition:-

    try { 
        // code that might cause an error goes here 
    } catch (error) { 
        // error message or other response goes here 
    } 

The try portion is where you would put any code that might throw an error. In other words, all significant code should go in the try section. The catch section will also hold code, but that section is not vital to the running of the application. So, if you removed the try-catch statement altogether, the section of code inside the try part would still be the same, but all the code inside the catch would be removed.

If any error occurs during the try portion, the try section is exited and the catch section is executed. The catch portion of the statement will receive a JavaScript object containing error information. The error identifier is required, but can be any custom name you choose. For example, the following would be the same as the previous code example:

try { 
        // code that might cause an error goes here 
    } catch (watermelon) { 
        // error message or other response goes here 
    } 

In the above example, the “error” identifier has been changed to “watermelon”, but will have the same results. Obviously, a name like “watermelon” would be counterproductive, but this simply serves to demonstrate that the name is flexible, but is required.

The Try-Catch Statement Example:-

 public class TestExceptionB{
   public static void main(String[]args){
      int sum = 0;
      for(int i=0; i<args.length; i++){
         try{
            sum += Integer.parseInt(args[i]);
         }catch(NumberFormatException e){
            System.out.println(”Index : ”+i+” is not integer.”+e);
         }
      }
      System.out.println(”Sum:” +sum);
   }
 }

This program works if all or any of the command-line arguments are not integers.

1. Compile : javac TestExceptionB . java
2. Run : java TestExceptionA 2 4 s i x 8
3. Output: Index value of array 2 is not integer. java.lang.NumberFormatException:
invalid character at position 1 in six, Sum: 14

When Should you Use Try-Catch?

The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users’ benefit. If you haven’t figured it out yet, when you execute a try-catch statement, the browser’s usual error handling mechanism will be disabled.

You can probably see the possible benefits to this when building large applications. Debugging every possible circumstance in any application’s flow is often time consuming, and many possibilities could be inadvertantly overlooked. Of course, with proper bug testing, no area should be overlooked. But the try-catch statement works as a nice fallback in areas of your code that could fail under unusual circumstances that were not foreseen during development.

Another benefit provided by the try-catch statement is that it hides overly-technical error messages from users who wouldn’t understand them anyhow.

The best time to use try-catch is in portions of your code where you suspect errors will occur that are beyond your control, for whatever reasons.

When Should try-catch be Avoided?

You shouldn’t use the try-catch statement if you know an error is going to occur, because in this case you would want to debug the problem, not mask it. The try-catch statement should be executed only on sections of code where you suspect errors might occur, and due to the overwhelming number of possible circumstances, you cannot completely verify if an error will take place, or when it will do so. In the latter case, it would be appropriate to use try-catch.

Example:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Click OK to continue viewing this page,\n";
  txt+="or Cancel to return to the home page.\n\n";
  if(!confirm(txt))
    {
    document.location.href="http://www.w3schools.com/";
    }
  }
}
</script>
</head>
<body>
<input type="button" value="View message" onclick="message()" />
</body>
</html>

Java Exceptions in Java with Example Programs

Exception:-

Exceptions are a mechanism used by many programming languages to describe what to do when errors happens. There are two types of exceptions in Java programming, known as checked and unchecked exceptions. Checked exceptions are those that the programmer can easily handle this type of exceptions like: file not found, and network failure etc. Unchecked exceptions are arises from the conditions that are difficult for programmers to handle. Unchecked exceptions are called runtime exceptions. In Java, Exception class is the base class that represents checked and unchecked exceptions and RuntimeException class is the base class that is used for the unchecked exceptions.

Example 1: Throwing an Exception

 public class TestExceptionA{
   public static void main(String[]args){
      int sum = 0;
      for(int i=0; i<args.length; i++){
         sum += Integer.parseInt(args[i]);
      }
      System.out.println(”Sum:” +sum);
   }
 }

This program works if all of the command-line arguments are integers.

Compile : javac TestExceptionA . java

Run: java TestExceptionA 2 4 6 8

Output: 20

But this program fails if any of the arguments are not integers;

Run: java TestExceptionA 2 4 s i x 8

Output: Runtime Except ion

Class Exception:-

               java.lang.Object
                  ~java.lang.Throwable
                       ~java.lang.Exception

Direct Known Subclasses:-

AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BackingStoreException, BadLocationException, CertificateException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, DestroyFailedException, ExpandVetoException, FontFormatException, GeneralSecurityException, GSSException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvalidMidiDataException, InvalidPreferencesFormatException, InvocationTargetException, IOException, LastOwnerException, LineUnavailableException, MidiUnavailableException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, ParserConfigurationException, PrinterException, PrintException, PrivilegedActionException, PropertyVetoException, RefreshFailedException, RemarshalException, RuntimeException, SAXException, ServerNotActiveException, SQLException, TooManyListenersException, TransformerException, UnsupportedAudioFileException, UnsupportedCallbackException, UnsupportedFlavorException, UnsupportedLookAndFeelException, URISyntaxException, UserException, XAException

Example 2: Throwing an Exception

<?php
function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    else return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello World';
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example 3: Nested Exception

<?php

class MyException extends Exception { }

class Test {
    public function testing() {
        try {
            try {
                throw new MyException('foo!');
            } catch (MyException $e) {
                /* rethrow it */
                throw $e;
            }
        } catch (Exception $e) {
            var_dump($e->getMessage());
        }
    }
}

$foo = new Test;
$foo->testing();

?>

The above example will output:

string(4) "foo!"


If you use the set_error_handler() to throw exceptions of errors, you may encounter issues with __autoload() functionality saying that your class doesn't exist and that's it.

If you do this:

<?php

class MyException extends Exception
{
}

class Tester
{
    public function foobar()
    {
        try
        {
            $this->helloWorld();
        } catch (MyException $e) {
            throw new Exception('Problem in foobar',0,$e);
        }
    }
  
    protected function helloWorld()
    {
        throw new MyException('Problem in helloWorld()');
    }
}

$tester = new Tester;
try
{
    $tester->foobar();
} catch (Exception $e) {
    echo $e->getTraceAsString();
}
?>

The trace will only show $tester->foobar() and not the call made to $tester->helloWorld().

In other words, if you pass a previous exception to a new one, the previous exception's stack trace is taken into account in the new exception.

To continue the execution code after throw new Exception, goto operator can be used, like this:

<?php
try {
    echo 'one';
    throw new Exception('-error-'); a:
    echo 'two';
} catch (Exception $e) {
    echo $e->getMessage();
    goto a;
}
//output: one-error-two
?>
But, goto operator can NOT be evaluate or get a value:
<?php
eval('goto a;'); //Fatal error: 'goto' to undefined label 'a'
$b = 'a';
goto $b; //Parse error: syntax error, unexpected T_VARIABLE, expecting T_STRING
?>

If you intend on creating a lot of custom exceptions, you may find this code useful.  I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes.  It also properly pushes all information back to the parent constructor ensuring that nothing is lost.  This allows you to quickly create new exceptions on the fly.  It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
    /* Protected methods inherited from Exception class */
    public function getMessage();                 // Exception message
    public function getCode();                    // User-defined Exception code
    public function getFile();                    // Source filename
    public function getLine();                    // Source line
    public function getTrace();                   // An array of the backtrace()
    public function getTraceAsString();           // Formated string of trace
  
    /* Overrideable methods inherited from Exception class */
    public function __toString();                 // formated string for display
    public function __construct($message = null, $code = 0);
}

abstract class CustomException extends Exception implements IException
{
    protected $message = 'Unknown exception';     // Exception message
    private   $string;                            // Unknown
    protected $code    = 0;                       // User-defined exception code
    protected $file;                              // Source filename of exception
    protected $line;                              // Source line of exception
    private   $trace;                             // Unknown

    public function __construct($message = null, $code = 0)
    {
        if (!$message) {
            throw new $this('Unknown '. get_class($this));
        }
        parent::__construct($message, $code);
    }
  
    public function __toString()
    {
        return get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
                                . "{$this->getTraceAsString()}";
    }
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
    try {
        throw new TestException();
    }
    catch (TestException $e) {
        echo "Caught TestException ('{$e->getMessage()}')\n{$e}\n";
    }
    catch (Exception $e) {
        echo "Caught Exception ('{$e->getMessage()}')\n{$e}\n";
    }
}

echo '<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
$0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
$1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
$2 {main}

PHP5 supports exception throwing inside a function, and catching it outside that function call. There is no mention of this in documentation but it works just fine, as tested by this sample code:

<?php

function exceptionFunction() {
        throw new Exception("Throwing an exception!");
}

try {
        exceptionFunction();
} catch (Exception $e) {
        echo "Exception caught!\n";
}

?>

The result in PHP 5.0.3 is "Exception caught!"

Further tests show that nested functions with exceptions, methods throwing exceptions, etc all work the same way. This is like declaring all classes (or methods) in Java as "class ClassName throws Exception". While I consider this a good thing, you should be aware that any thrown exception will propagate up your stack until it is either caught or runs out of stack.

About Java : Abstract Class vs Interface in Java Programming

Abstract and Interface:-

In Java technology, a java class can only extend another one class, but can implements one or more interfaces.

Example of Abstract and Interface Program:-

 abstract class Animal{

   public void type(){
     System.out.println(”Animal”);
   }

   public abstract void name();

 }

 interface Cat{
    public abstract void jump();
    void run(); // it will be automaticly public and abstract
 }

 interface Bird{
    void fly();
 }

 public class Tiger extends Animal implements Cat , Bird{

    public void fly(){
       System.out.println(”Tiger can’t fly”);
    }

    public void jump(){
       System.out.println(”Tiger can jump”);
    }

    public void run(){
       System.out.println(”Tiger can run”);
    }

    public void name(){
       System.out.println(”Tiger”);
 }

 public static  void main(String[]args){
     Tiger t = new Tiger();
     t.name();
     t.jump();
     t.run();
     t.fly();
   }
 }

A Excellent example of Abstract class vs Interface:-

One of the most frequent question in an interview for a Junior/Graduate Developer role is ‘What is the difference between Abstract class and Interface?’. I have to admit that (as a Graduate) I thought this was not a good question to gauge my skill as a developer. I thought my intrepidness or whatever that skill I thought I had was far more important than being able to answer the difference between abstract and interface.

A couple of promotions later, I am sitting at the other end of the table. Having the responsibility of asking that same question, I can start to see to why we need to know the answer. To know the difference between the two, a developer must think about abstraction and encapsulation; the two paradigm that Object Oriented Programming heavily relies on in modelling reality. Without inheritance and interfaces, we are stuck with complex trees of conditions, iterations and recursions that is probably duplicated again and again to describe a similar characteristic between two entities.
This post will discuss the difference between abstract and interface, along with an (awesome!!!) example – better than you’ve seen elsewhere.

Abstract Class:-

1. Cannot be instantiated.

2. Is a special type of class in which you can have members without implementation.

3. As we know in C#/VB/Java, a class can only inherit from 1 class. This also applies for Abstract Class.

4. Normally used for framework-type library classes: providing default behavior for some of its class members, but forcing the developer to implement others.

5. Is believed to be faster in Java, HOWEVER I cannot find the same claim in .Net. The speed difference is *probably* negligible and only relevant to the most academic field.

6. The aim: making sure something is *eventually* implemented.

7. A class can inherit an abstract class without implementing all its abstract method.

However only a class that has all its method implemented can be instantiated to an object.

1. IS-A relationship.

e.g. Student IS A Person, Employee IS A Person.

// 'framework library' for a person
// a person can enrol and submit
// however, the class that consume this framework library
// need to provide 'where' the paperwork need to be sent

public abstract Person{
    public abstract SendPaperWork(string paperwork)

    public void Enrol(){
        SendPaperWork("enrolment");
    }
    public void Submit(){
        SendPaperWork("report");
    }
}

// by inheriting Person abstract class
// we are enabling student to enrol and submit
// however, SendPaperWork need to be implemented
// because we need to tell it explicitly 'where'
// to send the enrolment/ submission

public class Student: Person{
    public override SendPaperWork(string paperwork){
        School.Send(paperwork);
    }
}

// an employee send the paperwork to a different 'place' than student

public class Employee : Person{
    public override SendPaperWork(string paperwork){
        Company.Send(paperwork);
    }
}

Interface:-

1. cannot be instantiated.

2. is a special type of abstract class in which all the members do not have any implementations.

3. enables polymorphism. A class can implement more than 1 Interfaces.

4. normally used for application classes: providing contract for ensuring interactibility.

5. the aim: making sure something is interchangeable.

6. A class that implements an Interface need to contain all the implementation, otherwise the compiler will throw an error.

7. CAN-DO relationship.

e.g. Student CAN enrol, Student CAN submit assignment.

public interface ICanEnrol{
    void Enrol();
}

public interface ICanSubmit{
    void Submit();
}

public class Student : ICanEnrol, ICanSubmit{
    public void Enrol(){
        School.Send("enrolment");
    }

    public void Submit(){
        School.Send("report");
    }
}

public class Employee : ICanEnrol, ICanSubmit{
    public void Enrol()
    {
        Company.Send("enrolment");
    }

    public void Submit(){
        Company.Send("report");
    }
}

public class MailServer{
    public void SendAllSubmissions(){

        // AllSubmitters is a collection of students and employees

        foreach (ICanSubmit submitter in AllSubmitters){

            // The MailServer does not care if
            // the submitter is a student
            // or an employee, as long as it can submit

            submitter.Submit()
        }
    }
}

With the rise of Aspect Oriented Programming and Domain Specific Language, we are starting to realise that Object Oriented Programming is not even rich enough (or too rich?) to model reality. It is difficult to handle cross cutting concerns using just inheritance and polymorphism. So it’s important to master these skills, because the answer is often not obvious. (Unfortunately) It took me a year after Uni (after I got my first job) to feel like I finally grasp these basic object oriented concept.

References:-

Geeks with blogs. Abstract Class vs Interface
Interfaces vs Abstract Class : Java Glossary

Declaring Interface Program in Java | Interface in Java

Declaring Interface:

In Java interfaces are declaring only the contract and no implementation, like a 100% abstract superclass. All methods declared in an interface are public and abstract (do not need to actually type the public and abstract modifiers in the method declaration, but the method is still always public and abstract). Interface methods must not be static. Because interface methods are abstract, they cannot be marked final, strictfp, or native. All variables in an interface are public, static, and final in interfaces. An interface can extend one or more other interfaces. An interface cannot implement another interface or class.

Declaring Interface Example:-

 interface Bounceable{
    public abstract void bounce();
    void setBounce(int b);
 }

 public class Tire implements Bounceable{
    public void bounce(){
      System.out.println(”Love”);
    }

    public void setBounce(int b){
      int a = b;
      System.out.println(a);
    }

    public static void main(String[]arge){
       Tire t = new Tire();
       t.bounce();
       t.setBounce(15);
   }
 }


Definition of Declaring Interfaces:

The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

Example:-

Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */
import java.lang.*;
//Any number of import statements

public interface NameOfInterface
{
   //Any number of final, static fields
   //Any number of abstract method declarations\
}

Interfaces have the following properties:-

    # An interface is implicitly abstract. You do not need to use the abstract keyword when declaring an interface.

    # Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

    # Methods in an interface are implicitly public.

Example:

/* File name : Animal.java */
interface Animal {

    public void eat();
    public void travel();
}


Implementing Interfaces:


When a class implements an interface, you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

Aclass uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

/* File name : MammalInt.java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   }

   public int noOfLegs(){
      return 0;
   }

   public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
}

This would produce following result:

Mammal eats
Mammal travels

When overriding methods defined in interfaces there are several rules to be followed:

Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.

The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.

An implementation class itself can be abstract and if so interface methods need not be implemented.

When implementation interfaces there are several rules:

    # A class can implement more than one interface at a time.

    # A class can extend only one class, but implement many interface.

    # An interface itself can extend another interface. An interface cannot extend another interface.

Extending Interfaces:

An interface can extend another interface, similarly to the way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface.

The following Sports interface is extended by Hockey and Football interfaces.

//Filename: Sports.java
public interface Sports
{
   public void setHomeTeam(String name);
   public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
   public void homeTeamScored(int points);
   public void visitingTeamScored(int points);
   public void endOfQuarter(int quarter);
}

//Filename: Hockey.java
public interface Hockey extends Sports
{
   public void homeGoalScored();
   public void visitingGoalScored();
   public void endOfPeriod(int period);
   public void overtimePeriod(int ot);
}

The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:

A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

public interface Hockey extends Sports, Event

Tagging Interfaces:

The most common use of extending interfaces occurs when the parent interface does not contain any methods. For example, the MouseListener interface in the java.awt.event package extended java.util.EventListener, which is defined as:

package java.util;
public interface EventListener
{}

An interface with no methods in it is referred to as a tagging interface. There are two basic design purposes of tagging interfaces:

Creates a common parent: As with the EventListener interface, which is extended by dozens of other interfaces in the Java API, you can use a tagging interface to create a common parent among a group of interfaces. For example, when an interface extends EventListener, the JVM knows that this particular interface is going to be used in an event delegation scenario.

Adds a data type to a class: This situation is where the term tagging comes from. A class that implements a tagging interface does not need to define any methods (since the interface does not have any), but the class becomes an interface type through polymorphism.

Java Interface Example:-

    /*
    Java Interface example.
    This Java Interface example describes how interface is defined and
    being used in Java language.
    
    Syntax of defining java interface is,
    <modifier> interface <interface-name>{
      //members and methods()
    }
    */
    
    //declare an interface
    interface IntExample{
    
      /*
      Syntax to declare method in java interface is,
      <modifier> <return-type> methodName(<optional-parameters>);
      IMPORTANT : Methods declared in the interface are implicitly public and abstract.
      */
    
      public void sayHello();
      }
    }

    /*
    Classes are extended while interfaces are implemented.
    To implement an interface use implements keyword.
    IMPORTANT : A class can extend only one other class, while it
    can implement n number of interfaces.
    */
    
    public class JavaInterfaceExample implements IntExample{
      /*
      We have to define the method declared in implemented interface,
      or else we have to declare the implementing class as abstract class.
      */
    
      public void sayHello(){
        System.out.println("Hello Visitor !");
      }
    
      public static void main(String args[]){
        //create object of the class
        JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
        //invoke sayHello(), declared in IntExample interface.
        javaInterfaceExample.sayHello();
      }
    }
    
    /*
    OUTPUT of the above given Java Interface example would be :
    Hello Visitor !
    */