Wednesday, February 15, 2012

Using try, catch, and finally blocks

Java's exception-handling code is specified within a try...catch...finally block.


The try block encloses the code that might cause an exception to occur. The code in the try block is called protected code.
// basic try statement syntax
try {
  // protected code
}
catch (ExceptionType1 Identifier1) {
  // exception-handling code
}
catch (ExceptionType2 Identifier2) {
  // exception-handling code
}

finally {
  // 0 or 1 finally clause
}
You use zero or more catch blocks. When present, catch blocks specify exception handlers for the types of exceptions thrown. If no exception is thrown, then the code in the catch block doesn't run because it isn't needed.
The finally block is optional if a try block already has an associated catch block. If you have a finally block, the code it contains always executes, regardless of whether exceptions are thrown or not. The only exception to this rule is if a System.exit occurs, in which case the application terminates without executing a finally block.
If an exception occurs in a try block and is not caught in a catch block, a finally block will execute, provided it is present. The application then terminates.

If required, you must explicitly throw the exception up the call stack. If no method handles the exception, the program terminates when the exception object reaches the top of the call stack.
Consider the code in which the tryValues method contains appropriate exception-handling code.

The method takes two parameters – x and y. It declares and initializes an array and then prints the value of each array element divided by y, within a loop.
public class TestExceptions {

  // Catch the exceptions within the method itself
  void tryValues (int x, int y) {

    boolean wasError = false ;
    int[] intArray = new int[5] ;
    for (int i=0; i < intArray.length - 1; i++ )
      { intArray[i] = i + 8 ; }
    try {
      for (int i = 0; i <= x - 1; i++) {
        System.out.println (intArray[i] / y) ;
      }
    }
    //...
You enclose any lines of code that could cause exceptions in a try block.

For example, an exception could be caused if x is larger than the size of the array, or y is equal to zero.
public class TestExceptions {

  // Catch the exceptions within the method itself
  void tryValues (int x, int y) {

    boolean wasError = false ;
    int[] intArray = new int[5] ;
    for (int i=0; i < intArray.length - 1; i++ )
      { intArray[i] = i + 8 ; }
    try {
      for (int i = 0; i <= x - 1; i++) {
        System.out.println (intArray[i] / y) ;
      }
    }
    //...
If an exception occurs in a try block, execution is immediately directed to a series of catch blocks following the try block, which include the error-handling code.

Generally, you include a catch block for each type of exception that might be thrown in the try block, although you can write a single catch block for all exceptions if you like. You should aim to catch and handle specific exceptions, rather than general ones.
try {
  for (int i = 0; i <= x - 1; i++) {
    System.out.println (intArray[i] / y) ;
  }
}
catch (ArrayIndexOutOfBoundsException e) {
  System.out.println ("Array bounds exceeded" ) ;
  wasError = true ;
}
catch (ArithmeticException e) {
  System.out.println ("Attempt to divide by zero" ) ;
  wasError = true ;
}
catch (Exception e) {
  System.out.println ("Unknown exception occurred: " + e) ;
  wasError = true ;
}
finally {
  if (wasError)
    System.out.println ("Ending tryValues with error" ) ;
  else
    System.out.println ("Ending tryValues without an error" ) ;
}
If an exception occurs, the catch blocks are checked in order, from top to bottom.

If the exception is of the appropriate type for one of the catch blocks, the statements within the catch block are executed and no further catch blocks are checked. So the order in which you position catch blocks is important.

13 comments:

I just see the post i am so happy to the communication science post of information's.So I have really enjoyed and reading your blogs for these posts.Any way I’ll be replay for your great thinks and I hope you post again soon...
Web Development Company in India

It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command.
Java Training in Chennai

It is a really informative article. Thanks for it.
tezlyrics.com

I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.
360DigiTMG data analytics course hyderabad
data science courses
business analytics course

This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
artificial intelligence ai and deep learning in indore

Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing.360digitmg


Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing.360digitmg

tricks, and secrets for The Sims 4 for PC.
This page contains a list of The Sims 4 cheats, Easter eggs, tips, and other secrets. The following list of Sims 4 cheats are designed specifically for PC.

I am unquestionably making the most of your site. You unquestionably have some extraordinary knowledge and incredible stories.
Data Science Training in Hyderabad
Data Science Course in Hyderabad

Think This Is Owsm Post, But If You Check This Meta Fx Global

It's a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work.
data scientist training in hyderabad

Post a Comment