Full Stack Web Development Internship Program
- 5k Enrolled Learners
- Weekend/Weekday
- Live Class
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 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.
Often times, the programmer finds the need to specify his/her own exception.
The reasons to introduce these exceptions could be as follows:
Java provides the user with two exceptions:
Moving on with this article on Custom Exceptions in Java.
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
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.
Course Name | Date | |
---|---|---|
Java Certification Training Course | Class Starts on 28th January,2023 28th January SAT&SUN (Weekend Batch) | View Details |
Java Certification Training Course | Class Starts on 25th February,2023 25th February SAT&SUN (Weekend Batch) | View Details |
edureka.co