Powered by Blogger.

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.

2 comments:

  1. I really enjoy the blog.Much thanks again. Really Great.
    Very informative article post. Really looking forward to read more. Will read on…


    oracle online training
    sap fico online training
    dotnet online training
    qa-qtp-software-testing-training-tutorial

    ReplyDelete
  2. I appreciate you sharing this article. Really thank you! Much obliged.
    This is one awesome blog article. Much thanks again.

    sap online training
    software online training
    sap sd online training
    hadoop online training
    sap-crm-online-training

    ReplyDelete