Wednesday, June 3, 2015

What is User-Defined Exception?

Developer can able to create their Own Exception Class by extending Exception Class from java.lang API. And the toString() method should be overridden in the user defined exception class in order to display meaningful information about the exception.

The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax. throw new MyException("I threw my own exception.") To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax:

public myMethodName() throws MyException

package com.java.learning;

/**
* @author Achappan
*
*/
public class MyOwnException extends Exception {
private int age;
public MyOwnException(int age) {
  this.age = age;
}
@Override
public String toString() {
 // TODO Auto-generated method stub return "Age cannot be negative "+age;
 }
}


package com.java.learning;
public class MyOwnExceptionClassTest
{
/** * @param args */
public static void main(String[] args) throws MyOwnException{
 int age = getAge();
  if (age < 0){
        throw new MyOwnException(age); }else{ System.out.println("Age entered is " + age);
   }
}
static int getAge(){ return -10; }
}

No comments: