
Play Store Application link – https://play.google.com/store/apps/details?id=com.ideepro.java25hours
Learn with youtube video-
💡Definition-
Generally, Exception disturbs the normal flow of program.
In java, Exception is an object, which is created when exceptional condition occurs.
– it contains all the information about the exception(type/class of exception and location in the code)
Note- Java includes default handler.
💡Exceptions hierarchy-

More Detailed diagram of Exception hierarchy-
Throwable
+-- Exception
| +-- IOException
| +-- SQLException
| +-- ClassNotFoundException
| +-- NoSuchMethodException
| +-- CloneNotSupportedException
| +-- InterruptedException
| +-- IllegalAccessException
| +-- InstantiationException
| +-- NoSuchFieldException
| +-- SecurityException
| +-- UnsupportedOperationException
| +-- ArithmeticException
| +-- NumberFormatException
| +-- StringIndexOutOfBoundsException
| +-- RuntimeException
| +-- IllegalArgumentException
| +-- NullPointerException
| +-- IndexOutOfBoundsException
| +-- ArrayStoreException
| +-- ClassCastException
| +-- IllegalStateException
| +-- EnumConstantNotPresentException
| +-- UnsupportedOperationException
| +-- ConcurrentModificationException
| +-- ArithmeticException
| +-- ArrayIndexOutOfBoundsException
+-- Error
+-- VirtualMachineError
| +-- OutOfMemoryError
| +-- StackOverflowError
+-- AssertionError
+-- LinkageError
| +-- ClassCircularityError
| +-- ClassFormatError
| +-- ExceptionInInitializerError
| +-- IncompatibleClassChangeError
| +-- NoClassDefFoundError
+-- ThreadDeath
+-- InternalError
+-- UnknownError
Here is a basic comparison of Throwable
, Error
, and Exception
in Java:
Comparison | Throwable | Error | Exception |
---|---|---|---|
Superclass | None | Throwable | Throwable |
Indicates serious problems | Yes | Yes | No |
Should be caught by application | No | No | Yes |
💡-[TYPES OF EXCEPTIONS]-
💡1-CHECKED EXCEPTION:–
💡2-UNCHECKED EXCEPTION:–
Here is a table comparing errors, checked exceptions, and unchecked exceptions in Java:
Comparison | Error | Checked Exception | Unchecked Exception |
---|---|---|---|
Definition | An error is a serious problem that occurs during the execution of a program, and it cannot be handled or recovered from. | A checked exception is an exception that is checked at compile-time. | An unchecked exception is an exception that is not checked at compile-time. |
When they occur | Errors occur when something goes wrong that is beyond the control of the program, such as running out of memory or encountering a hardware problem. | Checked exceptions can occur at any time during the execution of a program. Checked exceptions are not caused by code but other resources | Unchecked exceptions occur at runtime. Unchecked exceptions are caused by poor/bad programming. |
How they are handled | Errors cannot be handled or recovered from. They can only be logged or reported to the user. | Checked exceptions must be either caught or declared in the throws clause of a method. | Unchecked exceptions do not need to be caught or declared in the throws clause of a method. They should be handled by writing correct codes. |
Examples | Examples of errors include StackOverflowError, OutOfMemoryError, and VirtualMachineError. | Examples of checked exceptions include IOException, SQLException, and FileNotFoundException. | Examples of unchecked exceptions include NullPointerException, IndexOutOfBoundsException, and IllegalArgumentException. |
Subclasses of Exception class | Errors are subclasses of the Error class, which is a subclass of the Throwable class. | Checked exceptions are subclasses of the Exception class, except for the error and runtime exception classes. | Unchecked exceptions are subclasses of the RuntimeException class. |
Note – Examples of Error
include:
OutOfMemoryError
: Indicates that the Java Virtual Machine (JVM) has run out of memory.
import java.util.ArrayList;
public class OutOfMemoryErrorExample {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
while (true) {
list.add(1); // keep adding elements to the list
}
}
}
StackOverflowError
: Indicates that the stack has overflowed because of an infinite recursion.
public class StackOverflowErrorExample {
public static void main(String[] args) {
infiniteRecursion(); // call the method that causes the error
}
public static void infiniteRecursion() {
infiniteRecursion(); // call itself indefinitely
}
}
💡-[5 KEYWORDS USED IN EXCEPTION HANDLING]-
Here is a tabular comparison of the try
, catch
, throw
, throws
, and finally
keywords in Java:
Keyword | Description | Syntax |
---|---|---|
try | The try block is used to enclose code that may throw an exception. | try { ... } |
catch | The catch block is used to handle an exception that is thrown in the try block. | catch (Exception e) { ... } |
throw | The throw keyword is used to throw an exception manually. | throw new Exception("Something went wrong"); |
throws | The throws keyword is used in a method declaration to indicate that the method may throw a specified exception. | public void doSomething() throws Exception { ... } |
finally | The finally block is used to enclose code that should always be executed, whether an exception is thrown or not. | finally { ... } |
-[scenarios]-
Here is a comparison of the four different ways to handle exceptions in Java:
Construct | Description | Syntax | Example |
---|---|---|---|
Try with Catch | This construct includes a try block followed by a catch block. The try block contains code that may throw an exception, and the catch block contains code to handle the exception. This construct is used to handle a single exception. | try { | try { FileReader fr = new FileReader(“D://h.txt”); } catch (FileNotFoundException e) { e.printStackTrace(); } |
Try with multiple Catch blocks | This construct includes a try block followed by multiple catch blocks. Each catch block is used to handle a different exception. This construct is used to handle multiple exceptions of different types. | try { } catch (ExceptionType1 ex) { } catch (ExceptionType2 ex) { } | try { Class.forName(“Array.A”); FileReader fr = new FileReader(“D://h.txt”); } catch (ClassNotFoundException e) { } catch (FileNotFoundException e) { } |
Multiple exceptions in single Catch block | This construct includes a try block followed by a catch block that can handle multiple exceptions. | try { } catch (ExceptionType1 | ExceptionType2 ex) { } | try { Class.forName(“Array.A”); FileReader fr = new FileReader(“D://h.txt”); } catch (ClassNotFoundException | FileNotFoundException e) { } |
Try with Finally | This construct includes a try block followed by a finally block. The finally block is always executed, whether an exception is thrown or not. This construct is used to ensure that certain code is always executed, regardless of whether an exception occurs. | try { } finally { } | try { FileReader fr = new FileReader(“D://h.txt”); } finally { } |
Try, Catch, Finally | This construct includes a try block, one or more catch blocks, and a finally block. The catch blocks are used to handle exceptions, and the finally block is used to ensure that certain code is always executed. This construct is used to handle multiple exceptions and ensure that certain code is always executed. | try { | try { FileReader fr = new FileReader(“D://h.txt”); } catch (FileNotFoundException e) { e.printStackTrace(); } finally{ System.out.println(“abc”); } |
Try with Resource | This construct includes a try block that is followed by a resource declaration. The resource is an object that implements the AutoCloseable interface, and it is automatically closed when the try block is finished. This construct is used to ensure that resources, such as streams and connections, are properly closed after they are used. | try (ResourceType resource = new ResourceType()) { } catch (ExceptionType ex) { } | try (FileReader fr = new FileReader(“file.txt”)) { } catch (IOException e) { } |
NOTE– Finally block will not be executed if program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).
NOTE– Try with Resource – This is introduced in Java 7 –
Here is an example of how to manage a resource using the try
statement in Java 6 or earlier:
FileReader fr = null;
try {
fr = new FileReader("file.txt");
int c;
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This can be rewritten using the try-with-resources
statement in Java 7 or later as follows:
try (FileReader fr = new FileReader("file.txt")) {
int c;
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
💡Avoiding a Exception using throws keyword–
💡#Throws-
Its a keyword, used to declare the exception with method signature.
It can be applied on multiple exceptions at a time.
Example-
import java.io.IOException;
public class ThrowsExample {
public static void main(String[] args) throws IOException {
readFile();
}
public static void readFile() throws IOException {
throw new IOException("Error reading file");
}
}
💡Throwing a Exception using throw keyword-
💡#Throw-
Its a keyword, used to generate an exception inside the method.
It can only be applied on 1 exception at a time.
Example-
public class Example {
public static void main(String[] args) {
String name= "Kuldeep56";
if (!name.equals("Kuldeep")) {
throw new IllegalArgumentException("name must contain only word Kuldeep");
}
}
}
💡Creating Custom exception class –
To create a custom exception in Java, you can follow these steps:
1- Create a new class that extends the Exception
class or one of its subclasses.
For example:
public class MyCustomException extends Exception {
// ...
}
2- Add a constructor to the custom exception class. The constructor should accept a string message as an argument, which can be used to provide more information about the exception. You can also add additional constructors as needed.
For example:
public class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
Note- You can add additional methods or fields to the custom exception class as needed. For example, you might want to add a method that returns the error code associated with the exception.
4- To throw the custom exception, you can use the throw
keyword followed by a new instance of the exception class, like this:
try {
// code that might throw the exception
throw new MyCustomException("There was an error processing the request");
} catch (MyCustomException e) {
// handle the exception
}
5- To catch and handle the custom exception, you can use a try-catch
block as shown above. In the catch block, you can perform any necessary actions, such as logging the error or displaying an error message to the user.
Complete Example –
public class Main {
public static void main(String[] args) {
try {
// code that might throw the exception
throw new MyCustomException("There was an error processing the request");
} catch (MyCustomException e) {
// handle the exception
System.out.println(e.getMessage());
}
}
}
class MyCustomException extends Exception {
public MyCustomException(String message) {
super(message);
}
}
More code samples are here-
1- Checked exception handling with try catch
package exceptionHandling; import java.io.FileInputStream; import java.io.FileNotFoundException; public class ExChkdEx1 { public static void main(String[] args) { try { FileInputStream f = new FileInputStream("c://a.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } } }
2-Checked exception handling with try and multiple catch blocks
package exceptionHandling; import java.io.*; public class Extc1 { public static void main(String[] args) { try { Class.forName("Array.A"); FileReader fr = new FileReader("D://h.txt"); } catch (ClassNotFoundException e) { } catch (FileNotFoundException e) { } } }
package exceptionHandling; import java.io.*; public class Extc2 { public static void main(String[] args) { try { Class.forName("Array.A"); FileReader fr = new FileReader("D://h.txt"); } catch (ClassNotFoundException | FileNotFoundException e) { } } }
4- Checked exception handling with try catch finally
package exceptionHandling; import java.io.FileInputStream; import java.io.FileNotFoundException; public class ExChkdEx2 { public static void main(String[] args) { try { FileInputStream f = new FileInputStream("c://a.txt"); } catch (FileNotFoundException e) { e.printStackTrace(); } finally{ System.out.println("abc"); } }
package exceptionHandling; import java.io.FileInputStream; import java.io.FileNotFoundException; public class ExChkdEx3 { public static void main(String[] args) throws FileNotFoundException { FileInputStream f = new FileInputStream("c://a.txt"); } }
package exceptionHandling; public class UnChkdEx { public static void main(String[] args) { int a=10; int b=0; int c; c = a / b; System.out.println(c); } }
Interview Questions —
- What is difference between checked and unchecked exceptions?
- What is difference between throw and throws?