Create your custom exception in Android

Exception handling is one of the most important thing when we are developing application. A lot of programming languages has exception handling mechanism and has lot of pre-defined exception types. For example, FileNotFoundException, NullPointerException, etc.

Also, when we are developing an application, time to time we want to create own exception(s) for meaningful errors and easy handling. For example, UserNotFoundException, EmployeeAlreadyExistsException, etc.

How can we create our custom exception in Android?
Everyting we need is our exception class which is extends from an Exception class.

Let's create a UserNotFoundException.
public class UserNotFoundException extends Exception {

    public UserNotFoundException() {
        super("User not found.");
    }

}
That's all. Now, we are throwing an exception;
public User getUser(int userId) throws Exception {

    // get user from database
    User user = ...;
   
    // check user
    if (user == null)
        throw new UserNotFoundException();

    return user;
}
and catching
public void myFunction()
{

    try {
        User user=getUser(999);
    } catch (UserNotFoundException e) {
        // now, we know user cannot be found in database
        // write spesific log, show specific message to user, etc.
    }
 
}
Of course, you can extend your exception class for additional and detailed informations and properties.

1 comments:

Paxees said...

Nice Logics sir thanks please contact me i want more help from you
whatsapp/ +923412030258 , Or Facebook/www/facebook.com/xeeshanxami

Post a Comment