Results 1 to 1 of 1
  1. #1
    Java Exam is offline Member
    Join Date
    Dec 2011
    Rep Power

    Default Tutorial:Overview of Java Exceptions for the Java Certification Exam

    In this article, we will continue our in depth at Java Exceptions. We will describe how Java uses exceptions as a way of signaling problems when you execute a program and as a control mechanism through which a program may be able to recover from an exceptional event. This continues on from our coverage of Java Classes and is part of a larger series of articles to help you prepare for the java associate exam. The previous article in this series was, “Tutorial:In Depth View of Java Classes for the Java Certification Exam IV"

    Using Java Exceptions

    An exception in Java is an object that's created when an abnormal situation arises in your program. Exceptions can be created by the JVM, by standard library class methods, or by your application code. As we mentioned, Java uses exceptions to signal errors in your Java programs. An exception doesn't always indicate an error though but can also signal some particularly unusual event in your program that deserves special attention. A major benefit of having an error signaled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors. With many kinds of exceptions, you must include code in your program to deal with them in order to ensure that your code does not compile. These exceptions are referred to as checked exceptions. Unchecked exceptions are exceptions where you have the option of dealing with them or not.

    Exceptions should be reserved for the unusual or catastrophic situations that arises. A normal event such as inputting data data and should be handled without resorting to exceptions. This is because dealing with exceptions involves significant processing overhead. If your program is handling lots of exceptions it will run a lot slower than it should. An exception object has fields to store information about the nature of the problem. The exception is thrown when the object identifying the exceptional circumstance is tossed as an argument to a specific piece of program code that has been written specifically to deal with that kind of problem. The code receiving the exception object as a parameter is said to catch it. The situations that cause exceptions are quite diverse, but they fall into four broad categories, as shown in table below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-javaexceptions.jpg
    Table: Exceptions in Java

    Various Types of Exceptions

    An exception is always an object of some subclass of the standard class Throwable. This is true for exceptions that you define and throw yourself, as well as the standard exceptions that are defined in Java's standard packages. It's also true for exceptions that are thrown by methods in one or another of the standard packages. Two direct subclasses of Throwable, Error and Exception are the parent of all the standard exceptions. Both these classes have subclasses that identify specific exception conditions. The figure below shows the Throwable class hierarchy:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-throwableclasshierarchy.jpg
    Figure: Throwable Class Hierarchy

    Error Type Exceptions

    The exceptions that are defined by the Error class and its subclasses all represent conditions that you aren't expected to catch. Error has several direct subclasses including ThreadDeath, LinkageError, and VirtualMachineError that are classified as unchecked exceptions. There is little or nothing to do recover from these types of errors during the execution of the program.When they occur, you read the error message that is generated by the exception and try to figure out what might be wrong with your code to cause the problem.

    Runtime Type Exceptions

    Almost all the exceptions that are represented by subclasses of Exception are checked exceptions. These type of exceptions must include code in a program to handle the exceptions if they are thrown. In methods whose code has the potential to throw a checked exception, you must either handle the checked exception within the method or register that your method may throw such an exception. If you don't, your program will not compile.

    It is not required to catch exceptions of type RuntimeException. This is because the compiler allows you to ignore RuntimeException exceptions that generally arise because of serious errors in your code. In most cases there is little one can do little to recover the situation except in those few instances where it may be useful to include code to recognize these type of exceptions.

    Other Exception Subclasses

    All the other classes derived from the class Exception are checked exceptions so the compiler verifies that code is provided to handle the exception in a method where the exception may be thrown or that you've indicated that the method can throw such an exception. As long as you do one of these two tasks, your code will compile. Apart from those that are subclasses of RuntimeException, all exceptions thrown by methods in the Java class library are checked.

    How to Manage Exceptions

    If your code can throw exceptions other than those of type Error or type RuntimeException then you must do something about it. Whenever you write code that can throw a checked exception, you have a choice. You can supply code within the method to deal with any exception that is thrown, or you can essentially ignore it by enabling the method containing the exception throwing code to pass it on to the code that invoked the method.

    Defining the Exceptions that a Method Can Throw

    If you have a method that can throw an exception without being a subclass of RuntimeException nor of Error, then it could be an exception of type IOException for example, which can be thrown if your method involves some file input or output operations. If the exception isn't caught and disposed of in the method, you must at least declare that the exception can be thrown by adding a throws clause in the method signature. If you look at methods devoted to I/O operations than you can see some of these of these types of exceptions thrown by objects of classes IOException and FileNotFoundException. Neither of these is a subclass of RuntimeException or Error, so the possibility of an exception being thrown needs to be declared. Because the method can't handle any exceptions it might throw, if only for the simple reason that you don't know how to do it yet, it must be defined as:

    Java Code: Syntax for Throwing an Exception
    double myMethod() throws IOException, FileNotFoundException { 
       // Detail of the method code...
    The listing above illustrates that the declaration in the method to throw exceptions involves putting the throws keyword after the parameter list for the method. Then add the list of classes for the exceptions that might be thrown, separated by commas. The exception will propagate up to the method that calls the method throwing the exceptions. It must take account of the exceptions thrown by the other method. The calling method definition must either deal with the exceptions or declare that it can throw these exceptions as well. The compiler checks for this and your code does not compile if you don't do one or the other.

    Handling Any Exceptions

    If you want to deal with checked exceptions where they occur, you can include three kinds of code blocks in a method to handle them — try, catch, and finally blocks:
    • A try block encloses code that may give rise to one or more exceptions. Code that can throw an exception that you want to catch must be in a try block.
    • A catch block encloses code that is intended to handle exceptions of a particular type that may be thrown in the associated try block.
    • The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.

    Let's dig into the detail of try and catch blocks first and then come back to the application of a finally block a little later.

    Using the try Block

    When exceptions are thrown you normally want to catch these and report the location of an error in your program. When you want to catch an exception, the code in the method that could cause the exception to be thrown is enclosed in a try block. Code that can cause exceptions is not required to be in a try block, but without the try block, the method containing the code won't be able to catch any exceptions that are thrown and the method must declare that it can throw the types of exceptions that are not caught. A try block can be necessary if you want to catch exceptions of type Error or RuntimeException. A try block is simply the keyword try, followed by braces enclosing the code that can throw the exception. The syntax of the try block is shown below:

    Java Code: A try block
    try {
       // Code that can throw one or more exceptions
    Using the catch Block

    You enclose the code to handle an exception of a given type in a catch block. The catch block must immediately follow the try block that contains the code that may throw that particular exception. A catch block consists of the keyword catch followed by a single parameter between parentheses. The parameter identifies the type of exception that the block is to deal with. The listing below shows how to handle the exception enclosed between braces:

    Java Code: Syntax for Exceptions Handling
    try { 
       // Code that can throw one or more exceptions
    } catch(IOException e) { 
       // Code to handle the exception
    This catch block handles exceptions of type IOException or of any subclass of IOException. If other checked exceptions can be thrown that are not declared in the method signature, this won't compile.

    Bonding try and catch

    The try and catch blocks are bonded together. Never separate them by putting statements between the two blocks, or even by putting braces around the try keyword and the try block itself. If you have a loop block that is also a try block, the catch block that follows is also part of the loop. You can see this with a variation of the previous example.

    Using Multiple catch Blocks

    If a try block can throw several different kinds of exception, you can put several catch blocks after the try block to handle them:

    Java Code: Syntax for Multiple catch Blocks
    try { 
          // Code that may throw exceptions
       } catch(ArithmeticException e) { 
          // Code for handling ArithmeticException exceptions
       } catch(IndexOutOfBoundsException e) { 
          // Code for handling IndexOutOfBoundsException exceptions
        // Execution continues here...
    Exceptions of type ArithmeticException are caught by the first catch block, and exceptions of type IndexOutOfBoundsException are caught by the second. If an ArithmeticException is thrown, only the code in that catch block is executed. When it is complete, execution continues with the statement following the last catch block.

    When you need to catch exceptions of several different types that may be thrown in a try block, the order of the catch blocks can be important. When an exception is thrown, it is caught by the first catch block that has a parameter type that is of the same type or is a superclass of the type of the exception.

    This has implications for multiple catch blocks relating to exception class types in a hierarchy. The catch blocks must be in sequence with the most derived type first and the most basic type last. Otherwise, your code does not compile. The simple reason for this is that if a catch block for a given class type precedes a catch block for a type that is derived from the first, the second catch block can never be executed, and the compiler detects that this is the case.

    Suppose you have a catch block for exceptions of type ArithmeticException and another for exceptions of type Exception as a catch-all. If you write them in the following sequence, exceptions of type ArithmeticException could never reach the second catch block because they are always caught by the first:

    Java Code: Invalid catch block sequence
       try {
          // try block code
       } catch(Exception e) { 
          // Generic handling of exceptions
       } catch(ArithmeticException e) { 
          // Specialized handling for these exceptions
    In principle, if you're only interested in generic exceptions, all the error handling code can be localized in one catch block for exceptions of the superclass type. However, in general it is more useful and better practice to have a catch block for each of the specific types of exceptions that a try block can throw as this enables you to identify and deal with each type of exception individually.

    How to Catch Multiple Exception Types in a Block

    You can catch an exception that may be any of two or more different types in a single catch block. You specify the possible types for the catch block parameter separated by |. The listing below show how this can be done:

    Java Code: Syntax for Catching Exceptions
    try { 
           // Code that can throw exceptions 
          // of type ArithmeticException and ArrayStoreException...
       } catch(ArithmeticException|ArrayStoreException e) { 
          // Code to handle exception of either type...
    The catch block is executed if an exception of either type ArithmeticException or type ArrayStoreException is thrown in the try block. It can be useful when you want to handle exceptions of two or more different types in the same manner because it avoids having to write multiple catch blocks containing the same code. This can arise quite easily when you call several methods in a single block, each of which may throw an exception of a different type. When you want to handle more than one type of exception in the same way, you can use the multiple types form for the catch block parameter. It’s possible to still have multiple catch blocks, each of which may respond to one or more exception types.

    Using The finally Block

    The immediate nature of an exception being thrown means that execution of the try block code breaks off, regardless of the importance of the code that follows the point at which the exception was thrown. This introduces the possibility that the exception leaves your application in an indefinite state. You could have opened a database connection and then an exception was thrown leaving the database connection open.

    The finally block provides the means for you to clean up at the end of executing a try block. You use a finally block when you need to be sure that some particular code is run before a method returns, no matter what exceptions are thrown within the associated try block. A finally block is always executed, regardless of whether or not exceptions are thrown during the execution of the associated try block. If a file needs to be closed, or a critical resource released, you can guarantee that it is done if the code to do it is put in a finally block. The finally block has a very simple structure:

    Java Code: Syntax of finally block
    finally {
          // Clean-up code to be executed last
    Just like a catch block, a finally block is associated with a particular try block, and it must be located immediately following any catch blocks for the try block. If there are no catch blocks then you position the finally block immediately after the try block. Otherwise your program will not compile.

    How to Structure a Method

    You've looked at the blocks you can include in the body of a method, but it may not always be obvious how they are combined. The first thing to understand is that a try block plus any corresponding catch blocks and the finally block all bunch together in that order:

    Java Code: Structure of Exception Handling
    try { 
          // Code that may throw exceptions...
       } catch(ExceptionType1 e) { 
          // Code to handle exceptions of type ExceptionType1 or subclass
       } catch(ExceptionType2 e) { 
          // Code to handle exceptions of type ExceptionType2 or subclass
       ... // more catch blocks if necessary 
       } finally {
          // Code always to be executed after try block code 
    You can't have just a try block by itself. Each try block must always be followed by at least one block that is either a catch block or a finally block.

    You must not include other code between a try block and its catch blocks, or between the catch blocks and the finally block. You can have other code that doesn't throw exceptions after the finally block, and you can have multiple try blocks in a method. In this case, your method might be structured as shown in figure below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-exceptionhandlingstructure.jpg
    Figure: Exception Handling Structure

    The doFoo() method in the above figure deals with exceptions of either type MyException1 or MyException2 in the first catch block. The second catch block is executed for exceptions of type MyException3. The method can also throw two other types of exceptions that are not caught within the method, and these are identified in the throws clause that follows the parameter list for the method. The code in the finally block always gets executed, regardless of whether an exception is thrown or not.

    The Normal Execution of a Method with Try Block

    The first line of output from the TryBlockTest listing indicates that execution of the try block in main() has begun. The next block of output from the listing is the result of a straightforward execution of the divide() method:
    • Execution of divide() method
    • First try block in divide() entered
    • Code at end of first try block in divide()
    • finally block in divide()
    • result = 2

    No exceptions occur in divide(), so no catch blocks are executed. The code at the end of the divide() method, following the catch blocks, isn't executed because the return statement in the try block ends the execution of the method. The finally block in divide() is executed before the return to the calling method occurs. The sequence of execution when no exceptions occur is shown in the figure below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d1-execsequencewoexceptions.jpg
    Figure: Execution Sequence without Exceptions

    The figure above illustrates the normal sequence of execution in an arbitrary try-catch-finally set of blocks. If there's a return statement in the try block, this is executed immediately after the finally block completes execution so this prevents the execution of any code following the finally block. A return statement in a finally block causes an immediate return to the calling point, and the code following the finally block isn't executed in this case.

    Handling Execution When an Exception Is Thrown

    The next block of output corresponds to an ArithmeticException being thrown and caught in the divide() method:
    • First try block in divide() entered
    • Arithmetic exception caught in divide()
    • index = 0 Expression: array[0]/array[1] is 10/0
    • finally block in divide()
    • Executing code after try block in divide()
    • result = 2

    The exception is thrown because the value of the second element in the array x is zero. When the exception occurs, execution of the code in the try block is stopped, and the code that follows the catch block for the exception in the divide() method is then executed. The finally block executes next, followed by the code after the finally block. The value in the last element of the array isn't changed from its previous value, because the exception occurs during the computation of the new value, before the result is stored. The general sequence of execution in a try-catch-finally set of blocks when an exception occurs is shown in figure below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-execseqwithfinally.jpg
    Figure: Exception Execution Sequence

    Execution of the try block stops at the point where the exception occurs, and the code in the catch block for the exception is executed immediately. If there is a return statement in the catch block, this isn't executed until after the finally block has been executed. If an exception is thrown in a finally block, this will terminate the execution of the code in the finally block and the method. This can be seen in the following statement to the finally block in divide():

    Java Code:
    int result = array[index]/array[index+1];
    When ArithmeticException is thrown in the try block, the same exception is thrown in the finally block as a result of this statement. You will see from the output that the divide() method terminates and the exception is caught in main(). Try moving the statement to the catch block for ArithmeticException. You'll see that the finally block still executes even though an exception is thrown in the catch block.

    Handling Execution When an Exception Is Not Caught

    The next block of output is a consequence of the third call to the divide() method:
    • First try block in divide() entered
    • Index-out-of-bounds exception caught in divide()
    • array length = 3 index = 1
    • finally block in divide()
    • Executing code after try block in divide()
    • Index-out-of-bounds exception caught in main()
    • Outside first try block in main()

    These steps will cause an ArrayIndexOutOfBoundsException to be thrown in the try block, which is then caught. However, the code at the end of the method, which is executed after the finally block, throws another exception of this type. This can't be caught in the divide() method because the statement throwing it isn't in a try block. Because this exception isn't caught in the divide() method, the method terminates immediately at the point where the divide() method was called. This causes the code in the relevant catch block in main() to be executed as a consequence of the uncaught exception.

    An exception that isn't caught in a method is always propagated upward to the calling method. It continues to propagate up through each level of calling method until either it is caught or the main() method is reached. If it isn't caught in main(), the program terminates and a suitable message is displayed. This situation is illustrated in the figure below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-seqofexceptionevents.jpg
    Figure: Sequence of Exception Events

    The sequence of events in the above figure is shown by the numbers on the arrows. It shows method1() calling method2(), which calls method3(), which calls method4(), in which an exception of type Exception2 is thrown. This exception isn't caught in method4(), so execution of method4() ceases, and the exception is thrown to method3(). It isn't caught and continues to be thrown until it reaches method1() where there's a catch block to handle it.

    Using Nested try Blocks

    The figure below illustrates nested try blocks. The catch blocks for the outer try block can catch any exceptions that are thrown, but not caught, by any code within the block, including code within inner try-catch blocks. In the figure shown the catch block for the outer try block catches any exception of type Exception2. These exceptions could originate anywhere within the outer try block. The figure is shown below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-nestedtryblocks.jpg
    Figure: Example of Nested Try Blocks

    The figure shows two levels of nesting, but it is possible to specify more once you have understood how exceptions work.

    Rethrowing of Exceptions

    There are a number of situations where the calling program may need to know about an exception previously thrown because it affects the continued operation of the program or because the calling program may be able to compensate for the problem. In this case, you need to pass an exception that has been caught in the calling program in order to rethrow it from within the catch block using a throw statement. The listing below provides the syntax for this:

    Java Code: Rethrowing of Exceptions
    try { 
       // Code that originates an arithmetic exception
    } catch(ArithmeticException e) { 
       // Deal with the exception here throw e;	
       // Rethrow the exception to the calling program
    The throw statement is the keyword throw followed by the exception object to be thrown. The definition of exceptions, use exactly the same mechanism to throw them.

    Creating Exception Objects

    The exception object that is passed to a catch block can provide additional information about the nature of the problem that originated it. To better understand this, look at the members of the base class for exceptions Throwable because these are inherited by all exception classes and are therefore contained in every exception object that is thrown.

    Implementing The Throwable Class

    The Throwable class is the class from which all Java exception classes are derived—that is, every exception object contains the methods defined in this class. The Throwable class has five constructors:
    • Throwable() creates an object with no detail message.
    • Throwable(String message) create an object containing message as the message.
    • Throwable(String message, Throwable cause) creates an object containing message as the message and a second Throwable object, cause, specifying the cause of the exception.
    • Throwable(String message, Throwable cause, boolean suppress, boolean stackTrace) creates an object containing message as the message and a second Throwable object, cause, specifying the cause of the exception. If suppress is true, it allows exception to be suppressed in order to deliver this exception. If stackTrace is true, recording of the stack trace is enabled.
    • Throwable(Throwable cause) creates an object with the message cause.toString() if cause is not null, and cause as the cause of the exception.

    The constructors with Throwable parameters provide the basis for storing a reference to one exception inside another. The cause reference can be obtained by calling getCause() for a Throwable object. This allows exceptions to be chained, so when one exception has been thrown, you can create another exception that provides more information about the problem and record within it a reference to the original exception that caused the new exception to be thrown. Objects of type Throwable can contain the following information:
    • A message, which I have just referred to as being initialized by a constructor.
    • A Throwable object identifying the cause of the exception.
    • A record of the execution stack at the time the object was created.
    • A record of exceptions suppressed in order to deliver this exception.

    The execution stack keeps track of all the methods that are in execution at any given instant. It provides the means whereby executing a return gets back to the calling point for a method. The record of the execution stack that is stored in the exception object consists of the line number in the source code where the exception originates followed by a trace of the method calls that immediately precede the point at which the exception occurs. The Throwable class has a number of public methods that enable you to access the message, the cause, and the stack trace as shown in the table:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-throwableclasspublicmethods.jpg
    Table: Throwable Class Public Methods

    You can get the stack trace as an array of StackTraceElement references by calling getStackTrace() for a Throwable object. Each StackTraceElement object records information about the execution point in a method when the exception was thrown. There will be a StackTraceElement array element for each method in the call stack when the exception was thrown. The following StackTraceElement methods provide you with details of a stack trace entry:
    • getClassName() returns the fully qualified name of the class containing the execution point for this stack trace entry.
    • getFileName() returns the name of the source file containing the execution point. getLineNumber() returns the line number for the execution point in the source file. getMethodName() returns the name of the method containing the execution point.

    Another Throwable method, fillInStackTrace(), updates the stack trace to the point at which this method is called.

    Using Standard Exceptions

    The majority of predefined exception classes in Java don't provide detailed information about the conditions that created the exception. The type alone serves to differentiate one exception from another in most cases. This general lack of detailed information is because it can often be gleaned only by prior knowledge of the computation that is being carried out. This leads to the notion of defining your own exceptions.

    Defining Your Own Exceptions

    There are three basic reasons for defining your own exception classes:
    • You want to add information when a standard exception occurs, and you can do this by rethrowing an object of your own exception class.
    • You may have error conditions that arise in your code that warrant the distinction of a special exception class.
    • To consolidate exceptions into a smaller, more manageable set (making it easier on calling methods).

    As there's a lot of overhead in throwing exceptions, it is not a valid substitute for "normal" recovery code that you would expect to be executed frequently. If you have recovery code that is executed often, then it doesn't belong in a catch block, but rather in something like an if-else statement.

    Defining an Exception Class

    Your exception classes must always have Throwable as a superclass; otherwise, they camnot define an exception. You can also derive them from any of the standard exception classes, but best practice is to derive them from the Exception class or from a subclass of Exception. This allows the compiler to keep track of where such exceptions are thrown in your program and checks that they are either caught or declared as thrown in a method. If you use RuntimeException or one of its subclasses, the compiler checking for catch blocks of your exception class are suppressed. The listing below provides an example of a custom exception class:

    Java Code: Custom Exception Class
    public class MyAppProblemException extends Exception { 
      // Constructors 
       public MyAppProblemException(){ }	
       // Default constructor
       public MyAppProblemException(String s) { 
          // Call the base class constructor
    Throwing Your Own Exception

    As you saw earlier, you throw an exception with a statement that consists of the throw keyword, followed by an exception object. This means you can throw your own exception in a method with the following statements:

    Java Code: Exception Constructors
    MyAppProblemException e = new MyAppProblemException(); 
    throw e;
    The method ceases execution at this point—unless the preceding code snippet is in a try block with a catch block that catches this exception. The exception will be thrown to the calling program if it is not caught. The message in the exception object consists only of the qualified name of the exception class.

    If you want to add a specific message to the exception, you could define it as:

    Java Code:
    MyAppProblemException e = new MyAppProblemException(“My App has a problem.”);
    You're using a different constructor here. In this case the message stored in the superclass is a string that consists of the class name with the string passed to the constructor appended to it. The getMessage() method inherited from Throwable, therefore, returns a String object containing the following string:

    XML Code:
    “MyAppProblemException: My App has a problem.”
    You can also create an exception object and throw it in a single statement. For example:
    throw new MyAppProblemException(“Terrible difficulties”);
    In all the examples of throwing your own exception, the stack trace record inherited from the superclass Throwable is set up automatically. ]If you plan to use your exception type in a catch block to provide further information about an exception that has been thrown, you can make provision for recording the original exception:

    Java Code: Custom Exception Problem
    try { 
       // Code that may throw SomeException...
    } catch SomeException e) { 
       // Analyze the cause
       throw new MyAppProblemException(“Disaster strikes!”, e);
    This fragment throws an object of your exception class that you create with a constructor that accepts a second argument of type Throwable to record the previous exception object. This will enable the code that catches your exception to access the SomeException object that caused your exception to be thrown and extract information from that.

    Implementing an Exception Handling Strategy

    In terms of exception handling there are no hard-and-fast rules. Some situations may be correctable and enable the program to continue as if nothing happened. Others may require outputting to a stack trace and a fast exit by calling the exit() method in the System class. There are some of the things you need to consider when deciding how to handle exceptions. In our previous listings we looked at handling arithmetic and index-out-of-bounds exceptions in the divide() method. But this is not the optimum means of dealing with the exceptions in the program for the following reasons:
    • It does not make sense to catch the arithmetic exceptions in the divide() method without passing them on to the calling method since it is the calling method that set the data up, and only the calling program has the potential to recover the situation.
    • By handling the exceptions completely in the divide() method, this allows for the calling program to continue execution without any knowledge of the problem that arose. In a real situation this would undoubtedly create problems as any further calculations would proceed with erroneous data.

    An Example of an Exception Class

    Another option is to catch the exceptions in the method where they originate and then pass them on to the calling program. You could pass them on by throwing new exceptions that provide more granularity in identifying the problem through the use of more than one exception type or by using additional data within the new exception type. You could define more than one exception class of your own that represents an ArithmeticException, where each reflected the specifics of a particular situation. This situation is shown in the figure below:

    Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-catchandpassexceptions.jpg
    Figure: Catch and Passing of Exceptions

    The numbers on the arrows indicate the sequence. The figure above shows how two different circumstances causing an ArithmeticException in method2() are differentiated in the calling method, method1(). The method2() method can throw an exception either of type Exception1 or of type Exception2, depending on the analysis that is made in the catch block for the ArithmeticException type. The calling method has a separate catch block for each of the exceptions that may be thrown. You could also define a new exception class that had instance variables to identify the problem more precisely.


    We looked at exceptions and how to deal with them in your programs. Consider exception handling as an integral part of developing any Java programs. The robustness of the program code depends on how effectively you are able to deal with the exceptions that arise within a program. Remember that exceptions involve considerable overhead and should be reserved for only very unusual situations while problems arising in the normal course of events should be handled without recourse to throwing exceptions.
    Attached Thumbnails Attached Thumbnails Tutorial:Overview of Java Exceptions for the Java Certification Exam-d10-javaexceptions.jpg  
    Last edited by Java Exam; 06-04-2012 at 06:42 PM.

Similar Threads

  1. Replies: 0
    Last Post: 06-04-2012, 06:07 PM
  2. Replies: 0
    Last Post: 05-13-2012, 08:26 PM
  3. Replies: 0
    Last Post: 05-07-2012, 09:46 PM
  4. Replies: 0
    Last Post: 05-07-2012, 09:24 PM
  5. Replies: 0
    Last Post: 05-01-2012, 11:10 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts