An event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Exception Handling
A mechanism to handle errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage is to maintain the normal flow of the application.
Checked Exception
Checked at compile-time, can be recognized by the compiler, e.g. IOException, SQLException
Unchecked Exception
Checked at runtime, not recognized by the compiler, e.g. ArithmeticException, NullPointerException
Error
This is considered as an unchecked exception
Java catch block
Used to handle the Exception by declaring the type of exception within the parameter
Java Multi-catch block
A try block can be followed by one or more catch blocks, each containing a different exception handler
Why use Java finally block?
To put "cleanup" code such as closing a file, closing connection, etc. and to place important statements to be printed regardless of the exception occurring or not.
throw vs. throws
throw is used to explicitly throw an exception, throws is used in the method header to indicate what exceptions the method may throw
Java Custom Exceptions
Also known as user-defined exceptions, derived classes of the Exception class used to customize the exception according to the user need
NullPointerException
Thrown when a java program process an object which contains a null value
ArrayIndexOutOfBoundsException
Occurs while processing an array and asking for a position that does not exist within the size of the array
ArithmeticException
Occurs when an exceptional arithmetic condition has occurred, this often happens when a program attempts to divide by 0
NumberFormatException
An unchecked exception thrown by parseXXX() methods when they are unable to convert a string to a number
InputMismatchException
Thrown by a Scanner to indicate the token retrieved does not match the pattern for the selected type, or that the token is out of range for the expected type
FileNotFoundException
References to a file that cannot be found
IllegalArgumentsException
Calling a method with illegal arguments
StringIndexOutOfBoundsException
A string index is either less than 0 or greater than or equal to the length of the string
try
This keyword is used to specify a block where we should place an exception code
catch
This keyword is used to handle the exception
finally
This keyword is used to execute the necessary code of the program. It is executed whether an exception is handled or not
throw
This word is used to throw an exception
throws
This keyword is used to declare exceptions. It specifies that there may occur an exception in the method
try block
used to enclose the code that might throw an exception
catch block
used to handle the exception by declaring the type of exception within the parameter