Complete guide to Java Exception Handling
Content to be covered:
- Introduction of Java Exception Handling
- Java Catch & Multi Catch Block, e.getPrintMessage
- Java try catch and finally in-depth concept
- Java Exception Hierarchy
- Checked and Unchecked Exceptions
- How Do You Catch Errors in Java and How Are They Different from Exceptions?
- Understand when to use ‘throw’ vs ‘throws’ in Java
- Create an user-defined exception in Java in a easy way
Introduction of Java Exception Handling
public class ExceptionClass { public static void main(String[] args) { ExceptionClass obj = new ExceptionClass(); obj.unhandledException(); obj.handleException(); } }
void unhandledException() { int b = 0; int a = 100 / b; System.out.println(a); System.out.println("Done!"); }
void handleException() { int a = 0; int b = 0; try { // sensitive code a = 100 / b; System.out.println(a); } catch (ArithmeticException e) { System.out.println(e.getMessage()); Scanner sc = new Scanner(System.in); System.out.println("Choose non-zero value for b again: "); b = sc.nextInt();// non zero a = 100 / b; } // Rest of the code! System.out.println(a); System.out.println("Done!"); }
Java Catch & Multi Catch Block, e.getPrintMessage
void multipleCatch() { int a = 0; int b = 0; try { // sensitive code a = 100 / b; System.out.println(a); } catch (ArithmeticException e) { System.out.println(e.getMessage()); Scanner sc = new Scanner(System.in); System.out.println("Choose non-zero value for b again: "); b = sc.nextInt();// non zero a = 100 / b; } catch (InputMismatchException e) { System.out.println(e.getMessage()); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("Done!"); }
void inputMismatchException() { try { Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); int number = sc.nextInt(); System.out.println("You have entered: " + number); sc.close(); } catch (InputMismatchException e) { System.out.println("Input mismatch Issue!"); } //always run {Exception or no Exception} finally { System.out.println("Done1"); } System.out.println("Done2"); } void stackOverFlowError(int i) { try { while (i > 0) { i++; stackOverFlowError(i); } } catch (Exception e) { System.out.println(e.getMessage()); } // Rest of the code System.out.println("Done!"); } void indexOutOfBoundExceptionPart1() { int[] myNumbers = { 1, 2, 3 }; System.out.println(myNumbers[10]); System.out.println("DOne!"); } void indexOutOfBoundExceptionPart2() { try { int[] myNumbers = { 1, 2, 3 }; System.out.println(myNumbers[10]); } catch (Exception e) { System.out.println(e.getMessage()); } System.out.println("Done!"); } void uncheckedExceptions() { int b = 0; int a = 100/b; System.out.println(a); } void nullPointerException() { try { String s = null; System.out.println(s.charAt(0)); } catch (NullPointerException e) { System.out.println(e.getMessage()); } System.out.println("Done!"); }
Java try catch and finally in-depth concept
void tryCatchFinally() { int a = 100; int b = 0; int c = 0; Scanner sc = new Scanner(System.in); try { System.out.println("Enter the value of b: "); b = sc.nextInt();// non zero c = a / b; } catch (ArithmeticException e) { e.printStackTrace(); } catch (InputMismatchException e) { e.printStackTrace(); } finally { System.out.println("Inside Finally"); } System.out.println("Outside Finally"); }
Java Exception Hierarchy


Checked and Unchecked Exceptions
public class ExceptionHandlingInJava { public static void main(String[] args) throws ManualException{ ExceptionClass obj = new ExceptionClass(); obj.checkedException(); obj.uncheckedException(); } } class ExceptionClass { void uncheckedException() { int x = 0; int y = 10; int z = y / x; System.out.println(z); } void checkedException() { try { FileInputStream fe = new FileInputStream("/Desktop/Java/new.txt"); System.out.println(fe.hashCode()); } catch (FileNotFoundException e) { System.out.println("File does not exist!"); } } }
How Do You Catch Errors in Java and How Are They Different from Exceptions?
Understand when to use 'throw' vs 'throws' in Java: Full Simple Tutorial
public class ExceptionHandlingInJava { public static void main(String[] args) throws ManualException{ ExceptionClass obj = new ExceptionClass(); obj.useOfThrow(123); obj.useOfThrows(); } } class ExceptionClass { void useOfThrow(int age) throws Exception, ArithmeticException, IOException { if (age < 18) { throw new Exception(); } else { System.out.println("You are allowed to enter"); } } void useOfThrows() { try { useOfThrow(17); } catch (ArithmeticException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Creating a user-defined exception in Java is very easy
public class ExceptionHandlingInJava { public static void main(String[] args) throws ManualException{ ExceptionClass obj = new ExceptionClass(); obj.manualExceptionThrow(); obj.useOfThrowKeyword(); } } class ExceptionClass { void calculateArea(int r) throws ManualException { if (r < 0) { throw new ManualException(); } int area = r * r; System.out.println(area); } void useOfThrow() throws ManualException{ int b = 5; int a = 0; if (b==5) { throw new ManualException(); } a = 100/b; System.out.println(a); } void useOfThrowKeyword() { int b = 5; int a = 0; try { if (b==5) { throw new ManualException(); } a = 100/b; }catch(Exception e) { System.out.println(e.getMessage()); } System.out.println(a); } } class ManualException extends Exception { public String getMessage() { String detailMessage = "ManualException Occured!"; return detailMessage; } }
Questions for Practice:
Q1. Write a Java program to accept and print employee details at runtime. The details should include Employee ID, Name, and Department ID.
The program must validate the input data and raise appropriate exceptions if any of the following conditions are not met:
- The first letter of the employee name should be a capital letter.
- The employee ID should be an integer between 2001 and 5001 (inclusive).
- The department ID should be an integer between 1 and 5 (inclusive).
If any of the above conditions fail, the program should raise a specific exception with a clear message. Otherwise, it should display the entered employee details normally.
Q2. Power Calculator with Exception Handling: Create a class called MyCalculator with a method power(int n, int p) that calculates n raised to the power p (i.e., n^p).
Method Requirements:
1. If either n or p is negative, the method should throw an exception with the message:
“n or p should not be negative.”
2. If both n and p are zero, the method should throw an exception with the message:
“n and p should not be zero.”
3. Otherwise, return the value of n^p.
Input Format:
The input consists of multiple lines. Each pair of lines contains two integers: the first line has the value of n, and the second line has the value of p. The input is read using the Scanner class and continues until all input is processed using hasNext().
Output Format:
1. Print the result of n^p if valid.
2. Otherwise, print the appropriate exception message.
Project Title: Online Bank Account Management System
Project Summary:
Design and implement a simple Online Bank Account Management System using Java that demonstrates robust exception handling. The system should allow users to create accounts, deposit and withdraw money, and view their account balance. It must handle different runtime issues such as invalid input, negative deposit amounts, and withdrawal attempts exceeding the available balance. To manage these scenarios, use Java’s exception handling features including try
, catch
, finally
, multiple catch blocks, throw
, throws
, and user-defined exceptions. The goal is to ensure the application behaves reliably and gracefully under error conditions, promoting strong programming practices related to exception management.
Create a simple command-line bank account management system where users can:
Create an account
Deposit money
Withdraw money
View balance
The program should handle various exception scenarios using:
User-defined exceptions for custom error situations
try-catch-finally for safe execution
Multiple catch blocks for different exception types
throw and throws to handle and propagate errors
Core Features with Exception Use:
Feature | Exception Handling Involved |
---|---|
Invalid deposit amount | User-defined exception (InvalidAmountException ) |
Withdraw more than balance | User-defined exception (InsufficientFundsException ) |
Input mismatch (non-numeric) | InputMismatchException in catch |
General exception | Exception catch block |
Always close scanner | finally block |
Throw error manually | throw new InvalidAmountException(...) |
Propagate error | Method declares throws keyword |
Thanks and Regards,