Powered by Blogger.

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>

1 comment:

  1. 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