1) What is exception in Java?
Ans : An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. The exception is said to be thrown whenever an exceptional event occurs in java which signals that something is not correct with the code written and may give unexpected result.Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure etc.
2) What is error?
Ans :An Error indicates that a non-recoverable condition has occurred that should not be caught. Error, a subclass of Throwable, is intended for drastic problems, such as OutOfMemoryError, which would be reported by the JVM itself.
3) Which is superclass of Exception?
Ans :"Throwable", the parent class of all exception related classes.
4) What are the advantages of using exception handling?
Ans :Exception handling provides the following advantages :
- Separating Error Handling Code from "Regular" Code.
- Propagating Errors Up the Call Stack.
- Grouping Error Types and Error Differentiation.
5) What are the types of Exceptions in Java?
Ans :There are two types of exceptions in Java :
- Checked Exceptions or runtime exception
- Unchecked Exceptions
Checked Exceptions :Exception occur during runtime is called checked exception.
Checked Exception should be thrown with keyword "throws" or should be
provided try catch block else program would not compile,we do get compilation error.
Some of the examples of checked exceptions are :
- IO exception
- File not found exception
- Class not found exception
Unchecked Exceptions :All subclasses of runtime exception are called unchecked exception.These are unchecked
exception because compiler does not check if a method handles or throws exception.
Some of the examples of unchecked exceptions are :
- Arthmetic exception
- Array index out of bound exception
- Null pointer exception
6) Exceptions are defined in which java package?
Ans : All the exceptions are subclasses of java.lang.Exception.
7) Explain Java Exception Hierarchy?
8) What are important methods of Java Exception Class?
Ans : Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable.
- String getMessage()
- String getLocalizedMessage()
- synchronized Throwable getCause()
- String toString()
- void printStackTrace()
9) What are the different ways to handle exceptions?
Ans :There are two ways to handle exceptions :
- Wrapping the desired code in a try block followed by a catch block to catch the exceptions.
- List the desired exceptions in the throws clause of the method and let the caller of the method handle those exceptions.
10) What are 5 exception handling keywords in java?
Ans :There are 5 keywords used in java exception handling.