Exception Handling in Java

Blog
Spread the love

Introduction

Exception:An unwanted unexpected event that disturbs the normal flow of the program is called an exception.

Example:

FileNotFoundException

SleepingException ..etc.

What is the meaning of exception handling?

Exception handling doesn’t mean repairing an exception. We have to define an alternative way to continue the rest of the program normally. This way of defining alternative is nothing but exception handling.

Example:Suppose our programming requirement is to read data from remote files located in the USA. At runtime if USA file is not available then our program should not be terminated abnormally.

We have to provide a local file to continue the rest of the program normally. This way of defining alternative is nothing but exception handling.

Example:

Java Exception Hierarchy: –

Exception HierarchyFollowing is the Exception Handling in Java handling hierarchy.

Throwable –

  • Throwable acts as a root for exception hierarchy.
  • It is in the java. lang package.

Error–

  • Subclass of Throwable
  • Most of the cases errors are not caused by our program, these are due to lack of system resources, and these are non-recoverable.

Example:If OutOfMemoryError occurs while being a programmer we can’t do anything the program will be terminated abnormally.System Admin or Server Admin is responsible to raise/increase heap memory.

Exception –

  • Subclass of Throwable.
  • Most of the cases exceptions are caused by our program and these are recoverable
  • Ex:If FileNotFoundException occurs then we can use local file and we can continue rest of the program execution normally.

Types of exception in Java

Checked Exceptions–

  • They are child classes of Exception except for RuntimeException.
  • The exceptions which are checked by the compiler whether programmer handling or not, for smooth execution of the program at runtime, are called checked exceptions.
  • Example –
    1. FileNotFoundException
    2. PenNotWorkingException
    3. HallTicketMissingException

UnChecked Exceptions–

  • They are child classes of RuntimeException.
  • The exceptions which are not checked by the compiler whether programmer handing or not, are called unchecked exceptions.
  • Example –
    1. ArithmeticException
    2. NullPointerException

Note:RuntimeException and its child classes, Error and its child classes are unchecked, and all the remaining are considered as checked exceptions.

Note:Whether an exception is checked or unchecked compulsory it should occur at runtime only and there is no chance of any exception occurring at compile time.

Fully checked –A checked exception is said to be fully checked if and only if all its child classes are also checked.

  • Example:
    1. IO Exception
    2. InterruptedException

Partially checked –A checked exception is said to be partially checked if and only if some of its child classes are unchecked.

Example: Exception

Java Exception Keywords

try This keyword is used to specify a block. In our program the code which may raise exception is called risky code, we have to place risky code inside try block.
catch This keyword must be preceded by a try block to handle the exception.
finally The main objective of finally block is to maintain cleanup code.
throw This keyword is used to throw an exception, sometimes we can create Exception object explicitly and we can hand over to the JVM manually by using throw keyword.
throws In our program if there is any chance of raising checked exception then compulsory, we should handle either by try catch or by throws keyword otherwise the code won’t compile.

Customized Exception Handling by using trycatch:In our program the code which may raise exception is called risky code, we have to place risky code inside try block and the corresponding handling code inside catch block.

Without try catch With try catch

extention_2024

extention_2024

extention_2024

extention_2024

Try with multiple catch blocks:an exception varies from exception to exception. Hence for every exception type it is recommended to take a separate catch block. That is try with multiple catch blocks is possible and recommended to use.

If try with multiple catch blocks present then order of catch blocks is very important. It should be from child to parent by mistake if we are taking from parent to child then we will get Compile time error saying.

Finally block:

  • It is not recommended to take clean up code inside try block because there is no guarantee for the execution of every statement inside a try
  • It is not recommended to place clean up code inside catch block because if there is no exception then catch block won’t be executed.
  • We require some place to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled. Such type of best place is nothing but finally block.
  • Hence the main objective of finally block is to maintain cleanup code.

Example:

extention_2024

Output:

extention_2024

Java Final vs Finally vs Finalize

Final Finally Finalize

Final is a keyword in java.

Finally, is a block in java.

Finalize is a method in java.

applicable for classes, methods and variables.

always associated with trycatch to maintain clean up code.

always invoked by Garbage Collector just before destroying an object to perform cleanup activities.

Java Throw Keyword:

we can create Exception object explicitly and we can hand it over to the JVM manually by using throw keyword.

Ex:

extention_2024

In this case creation of ArithmeticException object and handover to the jvm will be performed automatically by the main () method.

extention_2024

Output

extention_2024

Java Throws Keyword

In our program if there is any chance of raising checked exception then compulsory, we should handle either by try catch or by throws keyword otherwise the code won’t compile.

extention_2024

Output

extention_2024

We can handle this compile time error by using the following 2 ways.

By using try catch By using throws keyword

extention_2024

We can use throws keyword to delegate the responsibility handling to the caller method. Then the caller method is r handling that exception.extention_2024

Throw vs Throws –

Throw Throws

Throw keyword is used to throw an error explicitly.

Throws keyword is used to declare an exception.

Throw keyword is used within a method.

Throws keyword is used with the method signature.

Throw keyword cannot throw multiple exception.

Throws keyword can declare multiple exception.

Try With Resources –

Until 1.6 version it is required to write finally block to close all resources which are open as part of try block.

Problem in this approach:

programmer is required to close all opened resources with increases the
complexity of the programming

Compulsory we should write finally block explicitly which increases length of the code and reviews readability.

To overcome these problems Sun People introduced “try with resources” in 1.7 version.

Advantage of “try with resources” –the resources which are opened as part of try block will be closed automatically Once the control reaches end of the try block either normally or abnormally and hence, we are not required to close explicitly so that the complexity of programming will be reduced. It is not required to write finally block explicitly and hence length of the code will be reduced and readability will be improved.

Conclusions:

  1. We can declare any no of resources,but all these resources should be separated with (semicolon).
  2. All resource reference variables are implicitly final and hence we can’t perform reassignment within the try block.
  3. Untill 1.6 version try should be followed by either catch or finally but 1.7 version we can take only try with resource without catch or finally
bluethinkinc_blog

bluethinkinc_blog

2024-09-06

0

Leave a Reply

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

Find More Blogs

Exception Handling in Java

Spread the love Introduction – Exception:An unwanted

How to add custom less file in Magento2

Spread the love Source files *.css included into layout

Spring Boot Microservices

Spread the love Microservices architecture has become

Implementation of WireMock for better testing

Spread the love WireMock is a flexible and powerful tool

Magento 2: How to selected default option in configurable options?

Spread the love Configurable products in Magento 2 allow

How To Implement Simple JWT Authentication in Django Rest Framework

Spread the love We’ll learn how to use simple JWT

Optimizing Search: Integrating Elasticsearch in Django Applications

Spread the love What is Elasticsearch? Elasticsearch is a

How to create Customer Segments

Spread the love In Magento 2, “customer

Proxy Design Pattern and Requisition List in Magento 2

Spread the love Requisition List in Magento 2 Requisition

Google Ads Conversion Tracking Through Magento Platform:

Spread the love Google Ads Conversion Tracking Through

bluethinkinc Blogs