Share on Google+Share on Google+

The throw keyword example in java

Advertisement
This tutorial will demonstrate the use of the throw keyword. In this example you will see a sub-class is made of Exception. The throw keyword helps to call the subclass of Exception class that you made.

Code:

class MyMadeException extends Exception{}

class ExceptionExample
{
public static void main(String[] args)
{
String test = args[0];
try
{
System.out.println ("First");
doriskyJob(test);
System.out.println ("Forth");

} catch (MyMadeException e){
System.out.println ("Nothing");
}finally{
System.out.println ("Fifth");
}
System.out.println ("Sixth");
}
static void doriskyJob (String t) throws MyMadeException{
System.out.println ("Second");
if ("yes".equals(t)){
throw new MyMadeException();
}
System.out.println ("Third");
}
}

Hot to run program:

c:\yourjavadir> javac ExceptionExample.java

c:\yourjavadir> javac ExceptionExample Second

Output:

First
Second
Third
Forth
Fifth
Sixth

Advertisements

Posted on: March 31, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.