Exception Handling in Java: A Comprehensive Guide
Table of Content:
An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception handling, errors must be checked and handled manually—typically through the use of error codes.
AJava exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.
So, in short What is exception
exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
A user has entered an invalid data.
A file that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the JVM has run out of memory.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should
not try to catch.
Exception: Exception indicates conditions that a reasonable
application might try to catch.
Hierarchy of Java Exception classes
Exceptions are objects, and objects are defined using classes. The root class for exceptions is java.lang.Throwable
System errors are thrown by the JVM and are represented in the Error class. The Error class describes internal system errors, though such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully. Examples of subclasses of Error are listed in table below.
| Class | Reasons for Exception |
| LinkageError | A class has some dependency on another class, but the latter class has changed incompatibly after the compilation of the former class. |
| VirtualMachineError | The JVM is broken or has run out of the resources it needs in order to continue operating. |
Exceptions are represented in the Exception class, which describes errors caused by your program and by external circumstances. These errors can be caught and handled by your program. Examples of subclasses of Exception are listed in table below.
| Class | Reasons for Exception |
| ClassNotFoundException | Attempt to use a class that does not exist. This exception would occur, for example, if you tried to run a nonexistent class using the java command, or if your program were composed of, say, three class files, only two of which could be found. |
| IOException | Related to input/output operations, such as invalid input, reading past the end of a file, and opening a nonexistent file. Examples of subclasses of IOException are InterruptedIOException , EOFException (EOF is short for End of File), and FileNotFoundException |
Runtime exceptions are represented in the RuntimeException class, which describes programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors. Runtime exceptions are generally thrown by the JVM. Examples of subclasses are listed in table below.
| Class | Reasons for Exception |
| ArithmeticException | Dividing an integer by zero. Note that floating-point arithmetic does not throw exceptions (see Appendix E, Special Floating- Point Values). |
| NullPointerException | Attempt to access an object through a null reference variable. |
| IndexOutOfBoundsException | Index to an array is out of range. |
| IllegalArgumentException | A method is passed an argument that is illegal or inappropriate. |
Exception are categorized into 3 category.
- Checked Exception
The exception that can be predicted by the programmer at the compile time.Example : File that need to be opened is not found. These type of exceptions must be checked at compile time.
- Unchecked Exception
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of Bound exception. Unchecked exceptions are checked at runtime.
- Error
Errors are typically ignored in code because you can rarely do anything about an error. Example :if stack overflow occurs, an error will arise. This type of error cannot be handled in the code.
Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
1) Scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
int vara=50/0;//ArithmeticException
2) Scenario where NullPointerException occurs
If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
String strng=null; System.out.println(strng.length());//NullPointerException
3) Scenario where NumberFormatException occurs
The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
String strng="abc"; int i=Integer.parseInt(strng);//NumberFormatException
4) Scenario where ArrayIndexOutOfBoundsException occurs
If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below:
int array[]=new int[5]; array[10]=50; //ArrayIndexOutOfBoundsException
- Question 1: What is a finally block? When and how is it used? Give an example.
- Question 2: Name the block that encloses the code that may encounter anomalous situations.
- Question 3: How will you handle logical errors?
- Question 4: How will you handle compile-time errors?
- Question 5: What are logical errors? Why are they hard to find?
- Question 6: What are the types of compile-time errors?
- Question 7: How are compile-time errors different from run-time errors?
- Question 8: What are program errors? What are the types of program errors?
- Question 9: What would be printed by the following code segment if someValue equals 1000?
- Question 10: What is the difference between throw and throws clause?
- Question 11: What is the difference between Exception and Error?
- Question 12: How does a try statement determine which catch clause should be used to handle an exception?
- Question 13: What happens if a try-catch-finally statement does not have a catch clause to handle an exception thrown within the try block?
- Question 14: What class of exceptions are generated by the Java run-time system?
- Question 15: Can an exception be rethrown?
- Question 16: What classes of exceptions may be caught by a catch clause?
- Question 17: What is the purpose of the finally clause in a try-catch-finally statement?
- Question 18: What happens when you run a program that creates an array of ints and then sets a value beyond its length?
- Question 19: In which block can you throw the exception?
- Question 20: Which block traps and handles an exception?
- Question 21: Create a try block that can generate three types of exceptions and handle them with multiple catch blocks
- Question 22: What line of a given program will throw FileNotFoundException?
- Question 23: Write a try/catch block that throws an Exception if the value of variable X is less than zero. The exception should return message: "ERROR: Negative value in X coordinate".
- Question 24: Which code fragment will throw an ArrayIndexOutOfBoundsException?
- Question 25: Which of the following code fragments will throw an ArrayIndexOutOfBoundsException?
- Question 26: What is the throws keyword, and how does it differ from the throw keyword?
- Question 27: What type of exceptions do not require the caller to explicitly handle them?
- Question 28: What type of exceptions require the caller to explicitly handle them?
- Question 29: What is the root class for all exceptions?
- Question 30: How do you handle an exception? Describe the keyword try. How is it used?
- Question 31: How do you throw an exception?
- Question 32: Why is exception handling necessary?
- Question 33: What is the role of (i) throws keyword ? (ii) throw keyword ?
- Question 34: IOException is subclass of which exception class?
- Question 35: NumberFormatException is subclass of which exception class?
- Question 36: Which block is always executed no matter which exception is thrown?
- Question 37: Can one catch block sufficiently trap and handle multiple exceptions?
- Question 38: What are the three ways that an exception can be generated?
- Question 39: What are the two direct subclasses of the Throwable class?
- Question 40: Which of the following Java programs will result in a runtime error, and why?
public class RuntimeErrorExample { public static void main(String[] args) { int a = 10; int b = 0; int result = a / b; System.out.println("Result: " + result); } } - Question 41: Write general syntax of try-catch block
- Question 42: What is the difference between error and an exception?
- Question 43: Variable of the boolean type is automatically initialized as?
- Question 44: Which arithmetic operations can result in the throwing of an ArithmeticException?
- Question 45: What class of exceptions are generated by the Java run-time system?
- Question 46: When ArithmeticException is thrown?
- Question 47: When is the ArrayStoreException thrown?
- Question 48: Does it matter in what order catch statements for FileNotFoundException and IOException are written?
- Question 49: What is NullPointerException?
- Question 50: What things should be kept in mind while creating your own exceptions in Java?
- Question 51: How finally used under Exception Handling?
- Question 52: When throw keyword is used?
- Question 53: When throws keyword is used?
- Question 54: Which are the two subclasses under Exception class?
- Question 55: Explain Runtime Exceptions?
- Question 56: What do you mean by Checked Exceptions?
- Question 57: What is an Exception in Java?
- Question 58: How Java Handles Exceptions
- Question 59: What type of exceptions must be explicitly declared in a throws clause of a method?
- Question 60: The finally block is the last bit of code executed before your program ends. True or False? Explain.
- Question 61: What is wrong with this fragment?
- Question 62: Why do you need multiple catch handlers?
- Question 63: Advantages of Exception Handling
- Question 64: What are the advantages of exception handling?
- Question 65: What is the function of the catch block in exception handling? Where does it appear in a program? Solution:
- Question 66: When is Exception Handling required?
- Question 67: What are the types of program errors?
- Question 68: Example: OutOfMemoryError
- Question 69: Example: StackOverflowError
- Question 70: Example: NumberFormatException
- Question 71: Example: ArrayIndexOutOfBoundsException
- Question 72: Example: NullPointerException
- Question 73: Example: ArithmeticException
- Question 74: Example: IOException
- Question 75: Types of Exceptions
- Question 76: What is an Exception?