Thursday 20 August 2015

Simple Example For Creating Custom Exception Handling

Aim:

To understand how to create custom exception handling.


some application required meaningful exception based on application requirement. we create such type of exception by extending Exception class.

but when we create custom exception handling make that class extends RuntimeException because
to make custom exception handling is unchecked exception.


Example:

//TooSmallException.java

/**
 *
 */

/**
 * @author Kunal
 *
 */
public class TooSmallException extends RuntimeException
{

/**
*
*/
private static final long serialVersionUID = 1L;

public TooSmallException(String message) {
super(message);
}


 

}


//TooOldException.java


/**
 *
 */

/**
 * @author Kunal
 *
 */
public class TooOldException extends RuntimeException
{

/**
*
*/
private static final long serialVersionUID = 1L;

public TooOldException(String message) {
super(message);
}


}

//MainApps.java

/**
 *
 */

/**
 * @author Kunal
 *
 */
public class MainApps {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int age=Integer.parseInt(args[0]);
if(age<21)
{
throw new TooSmallException("You are Too Young for Marriage wait some time...!!");
}else if(age>50)
{
throw new TooOldException("You are too old for marriage..!!!");
}
else
{
System.out.println("we should get your match soon..!!");
}

}
}

Step to Run:

1. Compile all Java class
2. then run MainApp.java

:>java MainApp 35

we should get your match soon..!!


:>java MainApp 99

Exception in thread "main" TooOldException: You are too old for marriage..!!!
at MainApps.main(MainApps.java:23)

:>java MainApp 10

Exception in thread "main" TooSmallException: You are Too Young for Marriage wait some time...!!
at MainApps.main(MainApps.java:20)


here i run program from command prompt i.e why i passed argument to that

//In TooSmallException.java

called super("measg") to make description available to based class i.e Exception

if we not called for super(" meassge") then no description of exception is available.