Let us now implement a Java program to demonstrate the “throws” keyword. In this program, we have a class Examplethrow in which we have a method testMethod. In the signature of this testMethod, we declare two exceptions IOException and Arithmetic Exception using the throws keyword. Super and final keywords are two popular and useful keywords in Java. They also play a significant role in dealing with Java programs and their classes. In this chapter, you will learn about how to use super and final within a Java program.
Advertisements
Java throw keyword is used to throw an exception explicitly. The throw keyword must be in try block. When JVM encounters the throw keyword, it stops the execution of try block and jump to the corresponding catch block.
In the above example, statement 1 is validating the value of b, if b is zero then, throw an exception otherwise show the result.
Every time, when an exception occur, try block throws an exception to corresponding catch block. When we need a method to throw an exception, we use throws keyword followed by method declaration.
When a method throws an exception, we must put the calling statement of method in try-catch block.
In the above example, division() method is throwing an ArithmeticException, therefore, we have written the calling statement of division() method in try-catch block.
Finally block is used to cleanup resources allocated by try block, such as closing file, closing database connection, etc. The catch block is executed when the exception occur in try block. The finally block is used to execute a given set of statements, whether an exception has occurred or not. We can have only one finally block for each try block. It is not mandatory to have a finally block after try-catch block.
Keywords are words that have already been defined for Java compiler. They have special meaning for the compiler. Java Keywords must be in your information because you can not use them as a variable, class or a method name.
You can't use keyword as identifier in your Java programs, its reserved words in Java library and used to perform an internal operation.
abstract | assert | boolean | break |
byte | case | catch | char |
class | const | continue | default |
do | double | else | enum |
extends | final | finally | float |
for | goto | if | implements |
import | instanceof | int | interface |
long | native | new | package |
private | protected | public | return |
short | static | strictfp | super |
switch | synchronized | this | throw |
throws | transient | try | void |
volatile | while | true | false |
null |
true, false and null are not reserved words but cannot be used as identifiers, because it is literals of built-in types.