Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Exception Handling in Java

  • Programming with C Language Tutorial
    Programming with C Language Tutorial C Language
  • Maven Tutorial
    Maven Tutorial Important
  • Gautama Buddha life story in Hindi, Buddha's history
    Gautama Buddha life story in Hindi, Buddha’s history Biography
  • Learn MongoDB Tutorial, Installation, MongoDB DataTypes
    Learn MongoDB Tutorial, Installation, MongoDB DataTypes MongoDB
  • Elon musk Hindi : एलन मस्क हिंदी में, Autobiography,  Net Worth
    Elon musk Hindi : एलन मस्क हिंदी में, Autobiography,  Net Worth Biography
  • Jenkins java | Installing Jenkins on Windows
    Jenkins java | Installing Jenkins on Windows Important
  • Difference between Jenkins and TeamCity
    Difference between Jenkins and TeamCity, Maven, Octopus Differences
  • What is Computer
    What is Computer? Important

Exception Handling in Java

Posted on September 6, 2021October 19, 2021 By admin No Comments on Exception Handling in Java
Exception Handling in Java

In Java, by using exception handling technique in java we handle runtime errors to maintain the normal flow of the program and we avoid abnormal termination. In exception handling we define some alternative way by which we make the program to maintain the normal flow of the program even if there is an exception in the program.

Before going into details about exception handling let us understand what is exception, is it possible to remove exception completely, can exception occur during compile time?

Exception is actually an exceptional event, in other words we can say that it is an unexpected event which we do not want during the execution of the program. It disrupts the normal flow of the program. The exception comes during program execution.

The most important thing about exception is that all exceptions happen only at run time but compiler checks some exceptions at compile time, and JVM checks some exceptions at run time.

Table of Contents

  • Exception Hierarchy
    • Exception
    • Error
  • Checked Exception Vs Unchecked Exception
  • Fully Checked Vs Partially Checked
  • try…catch in exception handling
  • Try with multiple catch in exception handling
  • Finally Block in exception handing
  • throws clause in exception handling
  • throw clause in exception handling
  • Types of Exceptions
    • Built-in Exceptions
    • User-defined Exceptions

Exception Hierarchy

Throwable class is the root of the entire exception and it represents all errors and exceptions. In other words, we can say that Throwable class is the super class of all the exceptions in Java.

Thowable class has two child classes which are as follows:

  • Exception
  • Error

Exception

Exception is caused by our program which we write, we can handle it by writing program of exception handling.

Error

If this happens then we cannot do anything, that means we cannot handle the error. This is usually due to lack of resources.

Checked Exception Vs Unchecked Exception

Checked Exception: Exception which the compiler checks for smooth execution of the program.

Unchecked Exception: If JVM checks exception then we consider such exception as an unchecked exception.

You should know whether exception is “checked” type or “unchecked” type, but all exceptions are run time exceptions. Not likely to happen at compile time.

Fully Checked Vs Partially Checked

If all the child classes of a checked exception is checked type then we consider such exception as fully checked. For example, IOException.

If some of the child classes of the checked exception are unchecked then such type of exception we consider as partially checked. For example, Exception

In Java, the only two exceptions are partially checked exceptions which are Throwable and Exception.

try…catch in exception handling

By using try…catch block we handle the exception in java. Some code we write in try block and some code in catch block. Let’s see in details which code should we write in try and catch block.

                  try {
  // Code which may throw an exception
}
//catch and finally blocks . . .

                  try {
  // Code which may throw an exception
} catch (ExceptionType name) {
  // Block of code to handle errors
}

Try with multiple catch in exception handling

The order of the exception is very important if you use multiple catch block. You should write from child to parent. If you follow parent to child approach then you may get exception like “Exception XXXXX has already been caught“.

                  try {
  // Code which may throw an exception
} catch (ExceptionType name) {
  // Block of code to handle errors
} catch (ExceptionType name) {
  // Block of code to handle errors
}

Finally Block in exception handing

If you are using try…catch then sometime you may required to write the clean up code like setting null to object, closing the files and so on, in this case you should write the such code inside the finally block.

                  try {
  // Code which may throw an exception
} catch (ExceptionType name) {
  // Block of code to handle errors
} catch (ExceptionType name) {
  // Block of code to handle errors
}  finally {
  // Block of clean-up code
}

Finally block is the most important part of exception handling. Statements in the finally block will execute first, regardless of whether the return statement exists inside a try or catch block.

                  try {
   // Block of code  // Place 1
   return statement; // Place 2
} catch (ExceptionType name) {
  // Block of code to handle errors
} catch (ExceptionType name) {
  // Block of code to handle errors
}  finally {
  // Block of clean-up code // Place 3
}

Execution order:
Place 1
Place 3
Place 2

If we use System.exit(0) , the only condition is that the program flow will not come to finally block because JVM goes into shutdown in this case.

throws clause in exception handling

By using throws clause we can pass the responsibility of exception handling to the caller method.

throw clause in exception handling

As a programmer during programming sometimes we need to create a new object of exception and we want JVM to handle the exception. For such purpose we use throw keyword.

By using throw keyword we explicitly hand over the object of exception to JVM. We can use throw keyword to throw user defined exceptions in Java. And in most of the cases we use throw keyword for user defined exception.

You can use this technique if you required to show to custom message for the exception.

throw new IOException("This is custom message");

Types of Exceptions

There are following types of exception available in java:

Built-in Exceptions

These are the exception which are already available in Java. Whenever particular events occurs, JVM automatically raises these exception. For example,

ArithmeticException
ArrayIndexOutOfBoundsException
ClassNotFoundException
IOException

User-defined Exceptions

Sometimes we write a code to define our own exception which handles the exception as per our requirement. If the built-in exception is not able to describe a condition, we write a user-defined exception.

This program will show you how to do exception handling in Java using User Defined Exceptions.

                  class UserDefinedException extends Exception {
	public UserDefinedException(String s) {
		super(s);
	}
}

public class UserDefinedExceptionDemo {
	public static void main(String args[]) {
		try {
			throw new UserDefinedException("User Defined exception in GeekCer");
		} catch (UserDefinedException ex) {
			System.out.println("UserDefinedException Caught");

			ex.printStackTrace();
		}
	}
}

To find the difference between final, finally and finalize click here.

References:
https://docs.oracle.com/javase/tutorial/essential/exceptions/

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java

Post navigation

Previous Post: Importance of Thread Synchronization in Java
Next Post: JDBC Driver in Java

More Related Articles

Java LinkedList Java LinkedList Java
Difference between final, finally and finalize Difference between final, finally and finalize Differences
Loop in Java Loop in Java Java
Steps of Database Connectivity in Java Steps of Database Connectivity in Java Java
Object Oriented Programming Object Oriented Programming Java
Stack Vs Heap in Java Stack Vs Heap in Java | Memory Allocation Section in Java Differences

Related Posts

  • Java LinkedList
    Java LinkedList Java
  • Difference between final, finally and finalize
    Difference between final, finally and finalize Differences
  • Loop in Java
    Loop in Java Java
  • Steps of Database Connectivity in Java
    Steps of Database Connectivity in Java Java
  • Object Oriented Programming
    Object Oriented Programming Java
  • Stack Vs Heap in Java
    Stack Vs Heap in Java | Memory Allocation Section in Java Differences

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java Home
  • Java Comments
  • Java Variables
  • Java Data Types
  • Java Keywords
  • Java Operators
  • Java If-else Statement
  • Java Switch
  • Java Loop
  • Java Arrays
  • Method Overloading in Java
  • Java OOP
  • Java Collections
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Multithreading in java
  • Thread Synchronization
  • Exception Handling
  • Java JDBC Driver
  • Java Database Connectivity steps
  • Lambda Expressions
  • Concurrent Collections

Recent Posts

  • Structured Vs Unstructured Data in Hindi | Key Difference
  • Jhansi Ki Rani Lakshmi Bai History, Story, Information in Hindi
  • Elon musk Hindi : एलन मस्क हिंदी में, Autobiography,  Net Worth
  • World Environment Day in Hindi : Objective, Importance, Theme
  • Thomas Edison Biography in Hindi – थॉमस एडिसन जीवनी
  • International Nurses Day in Hindi | नर्स दिवस क्यों मनाते हैं?
  • Fork/Join Framework in Java | RecursiveTask, RecursiveAction
  • DBMS in Hindi | DBMS क्या है? | DBMS की विशेषताएं और प्रकार
  • Programming with C Language Tutorial
    Programming with C Language Tutorial C Language
  • Maven Tutorial
    Maven Tutorial Important
  • Gautama Buddha life story in Hindi, Buddha's history
    Gautama Buddha life story in Hindi, Buddha’s history Biography
  • Learn MongoDB Tutorial, Installation, MongoDB DataTypes
    Learn MongoDB Tutorial, Installation, MongoDB DataTypes MongoDB
  • Elon musk Hindi : एलन मस्क हिंदी में, Autobiography,  Net Worth
    Elon musk Hindi : एलन मस्क हिंदी में, Autobiography,  Net Worth Biography
  • Jenkins java | Installing Jenkins on Windows
    Jenkins java | Installing Jenkins on Windows Important
  • Difference between Jenkins and TeamCity
    Difference between Jenkins and TeamCity, Maven, Octopus Differences
  • What is Computer
    What is Computer? Important
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved