Throws and finally Keyword
It determines the exception types that a method may throw. It can also declare multiple exceptions. It is used for system exceptions. A try-catch block may be used to handle any exceptions that are caught. However, you must use the throws keyword to declare an exception.
Syntax:
modifier return-type method_name(type parameter) throws exception
Code Example
class M
{
static void fun() throws IllegalAccessException
{
System.out.println("Inside fun(). ");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
fun();
}
catch(IllegalAccessException e)
{
System.out.println("caught in main.");
} }
}
Finally
When an exception occurs, it is used to specify a block of the statement that must be performed. The try-or-catch block is always executed together with there. It is finally used for "cleanup" code, like terminating a file or connection.
Note:- If the JVM exits while the try or catch code is being executed, the finally block may not execute.
Code Example
class Ex
{
public static void main(String args[])
{
try
{
int num=12/0;
System.out.println(num);
}
catch(ArithmeticException e)
{
System.out.println("Number should not be divided by zero");
}
finally
{
System.out.println("This is finally block");
} }
}
FAQs
It determines the exception types that a method may throw. It can also declare multiple exceptions. It is used for system exceptions. A try-catch block may be used to handle any exceptions that are caught. However, you must use the throws keyword to declare an exception.
When an exception occurs, it is used to specify a block of the statement that must be performed. The try-or-catch block is always executed together with there. It is finally used for "cleanup" code, like terminating a file or connection.
RANREV INFOTECH