Java provides the user with the option to create their own exceptions. Such exceptions are known as Custom Exceptions or User-Defined Exceptions. In this article we will explore Custom Exceptions in Java.
Following pointers will be covered in this article,
Getting Started this article on Custom Exceptions in Java.
Custom Exceptions In Java
Custom exceptions can be created as follows,
[Java]
//class that represents user-defined exception
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
[/java]
//class that uses InvalidAgeException class Test{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("Invalid"); else System.out.println("Eligible to Drive"); } public static void main(String args[]){ try{ validate(15); }catch(Exception m){System.out.println("Exception: "+m);} System.out.println("Exit"); } }
Output:
Exception: InvalidAgeException:Invalid
Exit
Moving on with this article on Custom Exceptions in Java.
Need for Custom Exceptions
Often times, the programmer finds the need to specify his/her own exception.
The reasons to introduce these exceptions could be as follows:
- There are certain exceptions that are defined only for business logic and workflow. This enables the users to determine the source of the problem.
- To catch and handle the existing or the previously defined java exceptions.
Java provides the user with two exceptions:
- Custom Checked Exception
- Custom Unchecked Exception
Moving on with this article on Custom Exceptions in Java.
Custom Checked Exceptions
The custom checked exceptions are exceptions that extend java.lang.Exception. They are recoverable in nature and are handled explicitly. In the following example, a code is written to return the first line of the file as the output:
try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) return file.nextLine(); } catch(FileNotFoundException e) { }
The code throws the exception FileNotFound. The cause of this exception is unknown to the user. We are unaware of source of the exception, whether it has been caused due to the inexistence of the file, or due to an invalid file name. For implementing custom exception, the java.lang.Exception class is extended.
public class InvalidFileNameException extends Exception { public InvalidFileNameException(String errorMessage) { super(errorMessage); } }
A custom checked exception called InvalidFileNameException is created.
A constructor must be provided while creating the exception. In our case, the constructor takes String as the error message, and calls the parent class constructor.
try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) return file.nextLine(); }catch (FileNotFoundException e) { if (!isCorrectFileName(fileName)) { throw new InvalidFileNameException("Invalid filename : " + fileName ); } }
Although, the user is now aware of the exact exception, we have lost the root cause of the exception. This can be fixed by adding the java.lang.Throwable to the constructor. The InvalidFileNameException can now be used with the root cause of the exception:
public InvalidFileNameException(String errorMessage, Throwable err) { super(errorMessage, err); }
Moving on with this article on Custom Exceptions in Java
Custom Unchecked Exceptions
The custom checked exceptions extend java.lang.RuntimeException. They are unrecoverable in nature.
public class InvalidFileExtensionException extends RuntimeException { public InvalidFileExtensionException(String errorMessage, Throwable err) { super(errorMessage, err); } }
This exception is used as follows:
try (Scanner file = new Scanner(new File(fileName))) { if (file.hasNextLine()) { return file.nextLine(); } else { throw new IllegalArgumentException("File is not readable."); } } catch (FileNotFoundException err) { if (!isCorrectFileName(fileName)) { throw new InvalidFileNameException("Invalid filename : " + fileName , err); } } catch(IllegalArgumentException err) { if(!containsExtension(fileName)) { throw new InvalidFileExtensionException("Filename does not have any extension : " + fileName, err); } }
User-defined exceptions are essential as they enable us to define exceptions that are our own.
Thus we have come to an end of this article. If you wish to learn more, check out the Java Training by Edureka, a trusted online learning company. Edureka’s Java J2EE and SOA training and certification course is designed to train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.
Got a question for us? Please mention it in the comments section of this blog and we will get back to you as soon as possible.