Java Tutorial 24 – User Defined Exception
| More often than not, in your programming projects, you will be required to define custom Exceptions also called User-defined Exceptions. This can be done by extending the class Exception. |

There is no need to override any of the above methods available in the Exception class ,in your derived class. But practically, you will require some amount of customizing as per your programming needs.
Assignment: To created a User Defined Exception Class
Step 1) Copy the following code into the editor
class MyException extends Exception{
int a;
MyException(int b) {
a=b;
}
public String toString(){
return ("Exception Number = "+a) ;
}
}
class JavaException{
public static void main(String args[]){
try{
throw new MyException(2);
// throw is used to create a new exception and throw it.
}
catch(MyException e){
System.out.println(e) ;
}
}
}
Step 2) Save , Compile & Run the code. Excepted output -
![]()
NOTE:
The keyword “throw” is used to create a new Exception and throw it to the catch block.
