- What is an exception and exception handling?
There can be certain scenarios that may not be handled in the code correctly, in such situations program stops abruptly and we say an exception has occurred.
For ex - Accessing element in an array which is beyond the set size of the array.
Handling situations which can break the code is called Exception Handling.
- What are the different types of exception?
Following are the two types of exception-
- Checked Exceptions - Also knows as Compile time exceptions. These are known exceptions as we get compilation error.
- Unchecked Exception - Also known as Runtime exceptions. These are not known and occur when we run the application.
- Give some examples of Checked and Unchecked Exceptions?
Examples of Checked Exceptions -
- IOException
- FileNotFoundException
- ClassNotFoundException
- SQLException
- InvocationTargetException
Examples of Unchecked Exceptions -
- ArrayIndexOutOfBoundException
- NullPointerException
- NumberFormatException
- ClassCastException
- StringIndexOutOfBoundException
- How is exception handling achieved?
Exception handling can be done by using try catch block or by using throws clause.
- Explain try catch block.
Try Catch block is used inside a method.
A set of statements that can cause exception are written inside try block and catch block is used to catch that exception.
A catch block can be used to catch multiple exceptions.
There can be only one try block but multiple catch blocks are allowed.
A try block can be present without catch block by using finally block but a catch block cannot be present without a try block.
- What is finally keyword?
Finally is used to create a block after try or try catch. When an exception occurs program stops and nothing gets executed after that but if we have something required to do after exception occurs(ex- closing a connection) then we can use finally block.
Whatever we write in finally block, gets executed even if exception occurs.
- Explain throw keyword.
Throw keyword is used to throw an exception by declaring the exception with the throws keyword in method signature.
Once the exception is thrown, no further steps are executed.