A built-in exception in Java is an exception that is pre-defined in the Java libraries.
In Java, there are several built-in exceptions that are used to handle common error conditions in Java programs.
Here are some of the most commonly used built-in exception classes in Java:
ArithmeticException: This exception is thrown when an exceptional arithmetic condition has occurred, such as division by zero.
NullPointerException: This exception is thrown when you try to access or perform an operation on a null reference.
ArrayIndexOutOfBoundsException: This exception is thrown when you try to access an array element with an invalid index, either too high or too low.
NumberFormatException: This exception is thrown when you try to convert a string to a numeric type, but the string is not a valid representation of a number.
IllegalArgumentException: This exception is thrown when an illegal or inappropriate argument is passed to a method.
IOException: This exception is the base class for all exceptions related to input and output operations.
FileNotFoundException: This exception is thrown when an attempt to open a file specified by a pathname fails.
ClassNotFoundException: This exception is thrown when an application tries to load a class through its string name but no definition for the specified class name could be found.
ClassCastException: This exception is thrown when an object is incompatible with the requested type for casting.
InterruptedException: This exception is thrown when a thread is waiting, sleeping, or otherwise occupied, and it is interrupted.
NoSuchElementException: This exception is thrown by various classes in the Java Collections Framework to indicate that there are no more elements available.
An Example of Built-in Exception in Java
Output
java.lang.ArithmeticException: / by zero Output: 0
2. User Defined Exceptions
Java provides many built-in exception classes but also allows us to create our own exception class, which is known as a Custom Exception or User-defined Exception in Java. The Custom Exception class is basically a subclass of the built-in class Exception, and it throws that exception using the "throw" keyword.
A Java custom exception is used to customize the exception according to the needs of the user.
Syntax of Custom Exception
Let's see the example given below and try to understand how to create custom exceptions or user-defined exceptions in Java.
Example of Custom (User defined) Exception in Java
Output
ERROR: Please pass valid roll number. Student record is available.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
Please share this article on social media to help others.
If you have any query or suggestion regarding this artical please share with us feedback@javabytechie.com