Exception Handling
Exception Handling
Sometimes, while executing programs, we get errors that influence the normal working of the program. Such errors are called exceptions and the method used to deal with these exceptions is known as exception handling.
Exceptions are of two types:
- Built-in exception
- User-defined exception
Built-in exceptions are available in Java libraries. These predefined exceptions can be used to explain certain error situations.
Users can also create their own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions.
A. Exception Keywords:
Exception handling is done with the help of these keywords:
- try: the try block is always accompanied by a catch or finally block. Try block is where the exception is generated.
- catch: catch block handles the exception that is generated in the try block.
- finally: finally is always executed whether there is an exception or not.
- throw: it is used to throw an single exception.
- throws: it declares which type of exception might occur.
B. Examples:
a. try…..catch:
Output:
b. multiple catch:
Output:
c. try…..finally:
Output:
d. try……catch…..finally:
Output:
e. throws:
Output:
f. throw keyword:
Output: