![]() |
VOOZH | about |
Exceptions in Java are events that occur during program execution and disrupt the normal flow of a program. Java provides many built-in exceptions to handle common runtime and compile-time errors. Developers can also create custom exceptions to handle application-specific error conditions.
Built-in exceptions are predefined exception classes provided by Java's standard library to handle common runtime and compile-time errors. They help identify and manage abnormal situations such as invalid input, file errors, arithmetic errors, and null references. Java automatically throws these exceptions when such conditions occur.
ArithmeticException occurs when an illegal arithmetic operation is performed, such as division by zero.
Can't divide a number by 0
NullPointerException occurs when a program tries to access a method or variable using a null reference.
NullPointerException..
StringIndexOutOfBoundsException occurs when an invalid index is used to access characters in a string.
StringIndexOutOfBoundsException
FileNotFoundException occurs when a specified file cannot be found or opened.
Output:
File does not existNumberFormatException occurs when a string cannot be converted into a numeric value.
Number format exception
ArrayIndexOutOfBoundsException occurs when an invalid array index is accessed.
Array Index is Out Of Bounds
IOException occurs when an input/output operation fails during file or stream processing.
Output:
Hello Geek!
Exception Output: null
NoSuchMethodException occurs when a requested method does not exist.
IllegalArgumentException occurs when a method receives an invalid argument.
Output :
Exception in thread "main" java.lang.IllegalArgumentException: Not Eligible for Voting
at GFG.print(File.java:13)
at GFG.main(File.java:19)
IllegalStateException occurs when a method is invoked at an inappropriate time or state.
Output :
Exception in thread "main" java.lang.IllegalStateException: Either one or two numbers are not Positive Integer
at GFG.main(File.java:20)
ClassNotFoundException occurs when the JVM cannot find a specified class at runtime.
java.lang.ClassNotFoundException: Class1 Class Not Found...
User-defined exceptions are custom exceptions created by programmers to handle application-specific error conditions that are not covered by Java's built-in exceptions.
Syntax:
class MyException extends Exception {
MyException() { }
MyException(String message) {
super(message);
}
}
Throwing a User-Defined Exception:
MyException me = new MyException("Exception details");
throw me;
Example
Runtime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0