Leon Anavi
IT Tips && Tricks

Java

Created: 06.10.2009 21:56 Last Modified: 06.10.2009 22:02 Views: 9087
Keywords: catch, error, exception, finally, Throwable, try

Finally Java Exceptions

Overview of Java Exceptions

As a fully object-orientated language Java provides powerful tools for error handling. Only objects of classes which extend class Throwable can be raised as exceptions. Two types of exceptions exist: checked and unchecked (errors and runtime exceptions). Most of the applications throw and catch objects of classes derived of class Exception.

Finally

The Java Error handling mechanisms is consisted of three important keywords: try, catch and finally. The existence of finally makes Java code more convenient and gives advantages compared to other programming languages such as native C++. The code situated at the block named finally is always executed even if an exception is not raised. Unlike catch finally is not mandatory.

Example

/**
 *
 * @author Leon Anavi
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try
        {
            if (0 == args.length)
            {
                throw new Exception("Bam!");
            }
        }
        catch(Exception Ex)
        {
            System.out.println( Ex.getMessage() );
        }
        finally
        {
            System.out.println( "Finally it is time for me." );
        }
    }

}

Output:

[leon@localhost dist]$ java -jar ExceptionsExample.jar
Bam!
Finally it is time for me.
[leon@localhost dist]$ java -jar ExceptionsExample.jar arg
Finally it is time for me.
[leon@localhost dist]$
Although useless the example application demonstrates how finally works. Both tests shows that no matter what happens finally is always executed.

Further Reading

Lesson: Exceptions

Class Reference

Class Exception


  Home | About | Contact | Disclaimer | Sitemap © 2009-2022 Leon Anavi. All rights reserved.