Core Java Tutorial

Core Java Tutorial

What is User defined Exceptions

User defined exception:

Java allows us to write own exception class for our project, we all know that all exceptions are subclasses of Exception.

Writing custom unchecked Exception

To create a unchecked exception, make your exception call to be a subclass of RuntimeException.

Example

public class UserException extends RuntimeException {

 public UserException() {

  // TODO Auto-generated constructor stub

  super("User Exception Invaild User");

 }

}

 

You can write your own condition when this exception should occur

 

public class UserProcess {

 voidregister(String name)

 {

  if (....) // verify the user and throw custom Exception

  {

   thrownewUserException();

  }

 }

}

Writing custom checked Exception

To create a unchecked exception, make your exception call to be a subclass of Exception

Example

public class UserException extends Exception {

 public UserException() {

  // TODO Auto-generated constructor stub

  super("User Exception Invaild User");

 }

}

 

 

public class UserProcess {

 voidregister(String name)

 {

  if (....) // verify the user and throw custom Exception

  {

   thrownewUserException();

  }

 }

}