Core Java - Exception Handling
Core Java - Exception Handling
3 throws keyword is used in method signature to declare the exceptions that can occur in Throw keyword is used in the method body to throw an exception.
the statements present in the method.
Example: Example:
//Declaring arithmetic exception using throws void myMethod() {
void sample() throws ArithmeticException{ try {
//Statements //throwing arithmetic exception using throw
} throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}
4 You can handle multiple exceptions by declaring them using throws keyword. You can throw one exception at a time.
Example:
//Declaring multiple exceptions using throws Example:
void myMethod() throws ArithmeticException, NullPointerException{ void myMethod() {
//Statements where exception might occur //Throwing single exception using throw
} throw new ArithmeticException("An integer should not be divided by zero!!");
}
1. Point of Usage.
throw keyword is used inside a function. It is used when it is required to throw an Exception logically.
throws keyword is in the function signature. It is used when the function has some statements that can lead to some
exceptions.
void Demo()
{
// Statements where exceptions might occur.
}
throw keyword is used to throw an exception explicitly. It can throw only one exception at a time.
throws keyword can be used to declare multiple exceptions, separated by comma. Whichever exception occurs, if matched
with the declared ones, is thrown automatically then.
3. Syntax.
Syntax of throws keyword includes the class names of the Exceptions to be thrown.
// throwing multiple exceptions by class names
void Demo() throws ArithmeticException, NullPointerException
{
// Statements where exceptions might occur.
}
4. Propagation of Exceptions.
throw keyword cannot propagate checked exceptions. It is only used to propagate the unchecked Exceptions that are not
checked using throws keyword.
throw:
public class GFG {
public static void main(String[] args)
{
// Use of unchecked Exception
try
{
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e)
{
e.printStackTrace();
}
}
}
Output:
java.lang.ArithmeticException: / by zero
at UseOfThrow.main(UseOfThrow.java:8)
throws:
import java.io.IOException;
Output:
THROW THROWS
commas.
throw keyword is used to throw an exception explicitly.
Only single exception is thrown by using throw. Multiple exceptions can be thrown by using throws.
throw keyword is used within the method. throws keyword is used with the method signature.
Syntax wise throw keyword is followed by the instance variable. Syntax wise throws keyword is followed by exception class names.
Checked exception cannot be propagated using throw only. Unchecked For the propagation checked exception must use throws keyword followed
throw
throws
4. You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws
IOException,SQLException.
5. checked exceptions can not be propagated with throw only because it is explicitly used to throw an particular exception. checked exception can be
propagated with throws.
Exception propagation: An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b(), which
calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these
methods catches the exception.
throw keyword is followed by an instance of Throwable class or one throws keyword is followed by one or more Exception class names
of its sub-classes. separated by commas.
throw keyword is declared inside a method body. throws keyword is used with method signature (method declaration).
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The core advantage of exception handling is to maintain the normal flow of the application.
Example:
Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.
1.Checked Exception
2.Unchecked Exception
3.Error
Difference between Checked and Unchecked Exceptions
1) Checked Exception
The classes which directly inherit Throwable class except RuntimeException and Error are known as checked exceptions e.g. IOException, SQLException etc. Checked exceptions are checked at
compile-time.
2) Unchecked Exception
The classes which inherit RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are
not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
try:
The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone.
catch:
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finally:
The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throw:
The "throw" keyword is used to throw an exception.
throws:
The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
Built-in Exceptions / Exceptions Types
Built-in exceptions are the exceptions which are available in Java libraries. Below is the list of important built-in exceptions in Java.
Arithmetic Exception
It is thrown when an exceptional condition has occurred in an arithmetic operation.
ArrayIndexOutOfBoundException
It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
IOException
It is thrown when an input-output operation failed or interrupted
InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is interrupted.
NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException
It is thrown when accessing a method which is not found.
NullPointerException
This exception is raised when referring to the members of a null object. Null represents nothing
NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
RuntimeException
This represents any exception which occurs during runtime.
StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size of the string
Note That
The try block cannot be present without either catch clause or finally clause.
Any code cannot be present in between the try, catch, finally blocks.
Short Summary of Exception Handling
An Exception is a run-time error which interrupts the normal flow of program execution.Disruption during the execution of the program is referred as error or exception.
A robust program should handle all exceptions and continue with its normal flow of program execution. Java provides an inbuilt exceptional handling method
Exception Handler is a set of code that handles an exception. Exceptions can be handled in Java using try & catch.
Catch block: If there is error in normal code, then it will go into this block