You are on page 1of 12
2104/22, 21:08 Exception Class in Java -Javatpoint case eM one) hitpstwwnjavatpoint.comvexcention-class-injava ane 2104/22, 21:08 Exception Class in Java -Javatpoint Exception Class in Java An error is a problem, bug, or human-created mistake that arises at the time of execution of a program. An exception interrupts the flow of the program and terminates it abnormally. The termination of the program abnormally is not recommended, and for that, we need to handle these exceptions, Java provides Java.lang.Exception class for handling the exceptions which inherit the properties and methods of Object and Throwable class Methods of java.lang. Throwable class addSuppressed(, _fillinStackTrace), -getCauseQ, —_getLocalizedMessage(, _getMessage(), getStackTrace)), getSuppressedQ,, initCause(, printStackTraceQ, printStackTrace0, printStackTrace), setStackTrace(), and toString(). Methods of java.lang.Object class clone(), equals0, finalize, getClass(), hashCode(), notify(), notifyAll, and wait0. The Exception class has a set of sub-classes for handling different types of exceptions such as IOException, NotBoundException, and NotOwnerException etc. All the subclasses of the Exception class are in the form of Throwable that indicates the conditions that an application wants to catch The Exception class provides the following 5 constructors 1. public Exception() case eM one) hitpstwwnjavatpoint.comvexcention-class-injava ana. 2110422, 21:07 Exceplio Class in Java -Javapoint The public Exception () construct an exception with a null detail message. The cause can be subsequently initialized by calling Throwable.initCause(Java.lang.Throwable). It is a default constructor and takes no parameters for message and Throwable cause. 2. public Exception(String message) The public Exception( String message) construct a new exception with the given detailed message. Just like the default constructor, the cause can be subsequently initialized by calling Throwable.initCause(Java.lang.Throwable). It is a parameterized constructor which takes a parameter of type String for detail message. The detail message is saved so that the Throwable.getMessage() method can retrieve it. Parameters a, message It is of type string for the error message or detail message. 3. public Exception(String message, Throwable cause) It is another variation of the Exception () constructor, which takes two parameters, i.e., message and cause. It constructs a new exception with the given detailed message and cause. The message associated with the cause will not be automatically included in the exception detail message, Parameters a, message Itis of type string for the error message or detail message. b, cause The cause is saved so that the Throwable.getCause() method can retrieve it. The null value defines that the cause is nonexistent or unknown. 4. public Exception(Throwable cause) It is another variation of the Exception () constructor, which takes only a single parameter, ie, cause, The constructor creates an Exception with the given cause and the detailed message of the cause. | detail message = (caus ull ? null : cause.toString0) It is mainly used for the exceptions, which are more than wrappers for other throwables. case eM one) hitpstwwnjavatpoint.comvexcention-class-injava ana 2104/22, 21:07 Exception Class in Java -Javatpoint a. cause The cause is saved so that the Throwable.getCause() method can retrieve it. The null value defines that the cause is nonexistent or unknown. 5. protected Exception(String message, Throwable cause, Boolean enableSuppression, Boolean writableStackTrace) It is a little different from the other constructors. It is also a parameterized constructor and takes 4 parameters, ie, message, cause, enableSuppression, and writableStackTrace. It creates an exception with the specified parameters. Parameters a. message Itis a detailed message. b. cause The cause is saved so that the Throwable.getCause() method can retrieve it. The null value defines that the cause is nonexistent or unknown. ¢. enableSuppre It is a Boolean value that defines whether the suppression is enabled or not. d. writableStackTrace Itis a Boolean value that defines whether the stack trace is writable or not. Create custom exceptions using the Exception class We have a series of predefined exceptions in Java. Many times, we need to create our own Exception for handling errors. We used the custom exception for customizing the exceptions as per the user need. Let's take some examples of the Exception class and understand how we can create our own Exception in Java CustomExceptionExamplet ; // import required classes and packages package javaTpoint Microsoftlava; import java.util.Scanner, InvalidAgeException by extending Exception class for create invalid age excepti Hitps:twwnjavatpoint.convexcention class-injava ana 2104/22, 21:07 Exception Class in Java -Javatpoint @SuppressWarnings("serial") class InvalidAgeException extends Exception { // parameterized constructor that accepts only detail message public InvalidAgeException (String message) { //calling parent Exception class constructor super(message); // create CustomException€xamplet class that uses custom exception InvalidAgeException public class CustomExce u nExample1 // create method checkEligibility() to check whether the given is valid for exam or not static void checkElig fi // use conditional statement to check age iffage < 18) // we throw InvalidAgeException when the age is less than 18 ity (int age) throws InvalidAgeException throw new InvalidAgeException("You are not eligible for the exam. Jelse { System.out printin("You are eligible for the exam. // main method start public static void main(String args()) { // create scanner class object to take input from user Scanner scan = new Scanner(System.in); // declare variable age to store the user input int age; ease cello rele eet from the user But printin("Please enter your agi Iitps zw javatpont.comfexcepton-class-irjava siz 2104/22, 21:07 Exception Class in Java -Javatpoint age = scan.nextintQ; scan.close(); try { // call method checkEligibility() to check whether the user is eligible for exam or not checkEligibility(age); ) catch (InvalidAgeException exception) { System.out.printin("We found an excaptio! // printing the message from InvalidAgeException object System.out printin(exception); Output: Bconsok # a xR EMO ev ave Custom®xceptionExample' [lava Application] C\Users\astogl \ p2\pooliplugins\org edipse ust openjdk hotspot Please enter your age: 2 We found an excaption: avaTpoint .microsoftJava.Tnvalidagetxception: You are not eligible for the exam.| Description: In the above code, we create a custom exception, InvalidAgeException, We take input from the user for checking whether the user is eligible for the exam or not. We call the checkEligibility() method by passing the user input to it. The checkEligibility() method checks whether the given age is greater than 18 or not because a user having age 18+ is eligible for the exam. The InvalidAgeException when it finds an age less than 18. The catch block in the 4 SCROLL TO TOP ill handle this Exception and print the detailed message of the Exception. hitpstwwnjavatpoint.comvexcention-class-injava ana 2104/22, 21:07 Exception Class in Java -Javatpoint CustomExceptionExample2.java // import required classes and packages package javaTpoint.Microsoftlava; import java.util Scanner; import java.util ArrayList; import java.utiLArrays; // create class AlreadyExistException by extending Exception class for checking whether the la @SuppressWarnings("serial") class AlreadyExistException extends Exception { // parameterized constructor that accepts only detail message publi { // calling parent Exception class constructor AlreadyExistéxception (String message) super(message); // create CustomExceptionExample2 class that uses custom exception AlreadyExistException public class CustomExcept { // create method checkExistence() to check whether the given language already exists in th nExample2 static void checkExistence (Arraylist languages, String language) throws AlreadyE { // use conditional statement to check the existence of the language if(languages.contains(language)\ // we throw AlreadyExistException when the language is already exist in the list throw new AlreadyExistException(language +" is already exist in the list); jelse { languages.add(language); ‘System.out.printIn(language + " is added to the ArrayList successfully.” for(int i = 0; i < languages.size(); i++) { System out printin(languages.getti): case eM one) Hitpstwwnjavatpoint.convexcention-class-injava m2 2104/22, 21:07 Exception Class in Java -Javatpoint // main method start public static void main(String args()) f // declare ArrayList with some languages Arraylist languages , JavaScript"); new — ArrayList<> (Arrays.asList("Java", "Python", // create scanner class object to take input from user Scanner sca new Scanner(System.in); // declare variable lang to store the user input String lang; // take input from the user System.out printin(“Enter language to enter in the ArrayList: lang = scan.nextLine(; scan.close(); try { // call method checkExistence() to check whether the language is already exist in the li checkExistence(languages, lang); } catch (AlreadyExistException exception) { System.out printin("We found an excapt // printing the message from AlreadyExistException object System.out printin(exception); case eM one) Hitpstwwnjavatpoint.convexcention-class-injava ana 230422, 21:07 Exception Clas in Java avatpoit ® Console aka/RE DEBE Ovo es “tsps Gasmbcapntagll Une Apptalion Uses ao a pol ago apo openfehonpct| = Enter language to enter in the ArrayList: Python Ne found an excaption: javaTpoint .MicrosoftJava.AlreadyExistException: Python is already exist in the list. Ovaeehe Description: In the above code, we create the custom exception AlreadyExistException, We take input from the user to add it in the languages ArrayList. We call the checkExistence() method by passing the user input and the languages ArrayList to it. The checkExistence) method checks whether the given language is available in the languages Arraylist or not. The method throws AlreadyExistException when it finds the user input language in the languages ArrayList. The catch block in the main() method will handle this Exception and print the detailed message of the Exception. If the checkExistence() method doesn't find the given language in the languages ArrayList, it will add the user input language in the languages ArrayList. [Youtube For Videos Join Our Youtube Channel: Join Now case eM one) hitpstwwnjavatpoint.comvexcention-class-injava ona 2104/22, 21:07 Feedback © Send your Feedback to feedback@javatpoint.com Help Others, Please Share Learn Latest Tutorials Splunk tutorial Splunk (/sTumblr tutorial Tumblr ER Programming tutorial R Programming Python Pillow tutorial Python Pillow Preparation Aptitude Aptitude case eM one) SPSS tutorial spss # React tutorial ReactIS, @RXIS tutorial RxlS 2 Python Turtle tutorial Python Turtle Logical Reasoning Reasoning hitpstwwnjavatpoint.convexcention-class-injava a) Swagger tutorial Swagger #Regex tutorial Regex 2 React Native tutorial React Native #Keras tutorial Keras 2 Nerbal Ability Verbal Ability Exception Class in Java -Javatpoint PSQL tutorial Transact-SQL #) Reinforcement learning tutorial Reinforcement Learning #) Python Design Patterns Python Design Patterns Interview Questions Interview Questions son. 2104/22, 21:07 Exception Class in Java -Javatpoint Company Interview Questions Company Questions Trending Technologies Artificial (AWS Tutorial 2 Selenium 2 Cloud Intelligence tutorial ‘Computing Tutorial AWS selenium tutorial Antticial Cloud Computing Intelligence fHadoop tutorial g,——ReactIS i) Data Science Angular 7 Tutorial Tutorial Tutorial Hadoop Reacts Data Science Angular 7 2 Blockchain AGit Tutorial 2 Machine 2 _DevOps Tutorial cit Learning Tutorial Tutorial Blockchain Machine Learning DevOps B.Tech / MCA (Data Structures DAA tutorial 2) Operating Seem ool tutorial DAA System tutorial hitpstwwnjavatpoint.com/excention-class-injava anne Exception Class in Java -Javatpoint 2104/22, 21:07 Data Structures Operating System 2 Computer 4 Compiler 2 Computer 2 Discrete ‘Network tutorial Design tutorial Organization and Mathematics Computer Network Compiler Design Architecture Tutorial Computer Diserete Organization Mathematics @ Ethical Hacking — (g_- Computer 2) Software htm! tutorial tori es Tutori eri ‘Tutorial Graphies Tutorial Engineering Web teemnoloay Ethical Hacking ‘Computer Graphies Software Engineering 2 Cyber Security 4 Automata 2 C Language ACH tutorial tutorial Tutorial tutorial cH Cyber Security Automata € Programming Pav tutorial 2 Net Python tutorial List of Framework Programs Java ‘torial Python Programs Net # Control i, Data Mining 2 Data Systems tutorial Tutorial Warehouse torial Data Mining Tutorial Control System Data Warehouse case eM one) hitpstwwnjavatpoint.comvexcention-class-injava sana

You might also like