Java Custom Exception
Custom exceptions are exceptions that we can create on our own by inheriting Exception class. This how we can use all the functionalities of the exception class. Java custom exceptions are used to customize the exception according to user need. Here is an example-
- package com.Akshay.exceptions;
- /**@author Akshay Ingole**/
- public class InvalidUserNameException extends Exception {
- private static final long serialVersionUID = 1L;
- InvalidUserNameException(String s) {
- super(s);
- }
- }
Now your test program is
- package com.Akshay.exceptions;
- /** @author Akshay Ingole**/
- public class TestException {
- public static void validateName(String name) throws InvalidUserNameException {
- if (" ".equalsIgnoreCase(name) || null == name)
- throw new InvalidUserNameException("Name is not valid");
- else
- System.out.println("Hello " + name);
- }
- public static void main(String args[]) {
- try {
- validateName("Akshay");
- validateName(" ");
- } catch (Exception e) {
- System.out.println("Exception occured: " + e);
- }
- }
- }
- Output
- Hello Akshay
- Exception occured: com.Akshay.exceptions.InvalidUserNameException: Name is not valid
Hope this will helps you.
Comments
Post a Comment