StackStalk
  • Home
  • Java
    • Java Collection
    • Spring Boot Collection
  • Python
    • Python Collection
  • C++
    • C++ Collection
    • Progamming Problems
    • Algorithms
    • Data Structures
    • Design Patterns
  • General
    • Tips and Tricks

Monday, May 26, 2014

Java 7 catching multiple exception types

 May 26, 2014     Java     No comments   

In Java 7 and later it is possible to avoid code duplication by using a single catch block to handle more than one type of exception. The bytecode generated for a single catch block handling multiple exceptions is smaller compared to an equivalent implementation with multiple catch blocks and thus considered better for performance.

Consider a simple example to read a file with numbers and create a list of numbers. In Java 6 and earlier, we do an implementation similar to the one below. Here we repeat the same exception handling code in each of the catch blocks.

public static List<Integer> readFile(String fileName) {
  List<Integer> myList = new ArrayList<Integer>();
  BufferedReader in = null;
  try {
    in = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = in.readLine()) != null)
        {
          int num = Integer.parseInt(line);
            myList.add(num);
        }
  } catch (NumberFormatException e) {
    // do some action
    e.printStackTrace();
  } catch (IOException e) {
    // do some action
    e.printStackTrace();
  } 
  finally {
    try {
      if ( in != null ) 
        in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return myList;
}
In Java 7 it is possible to specify a single catch block to handle multiple exceptions to eliminate duplicate code. Each of the exception types a catch block needs to handle is separated by a vertical bar "|". This implementation is considered efficient since the byte code generated is smaller.
public static List<Integer> readFileMultiCatch(String fileName) {
  List<Integer> myList = new ArrayList<Integer>();
  BufferedReader in = null;
  try {
    in = new BufferedReader(new FileReader(fileName));
        String line = null;
        while ((line = in.readLine()) != null)
        {
          int num = Integer.parseInt(line);
            myList.add(num);
        }
  } catch (NumberFormatException | IOException e) {
    // do some action
    e.printStackTrace();
  } 
  finally {
    try {
      if ( in != null ) 
        in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  return myList;
} 
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Java SerializationIn this article, we will work with Java Serialization to convert an object to byte stream and back. Java Serialization Introduction Serialization is… Read More
  • Approaches to write files in JavaThis article describes some of the common approaches to write files in Java. Using OutputStreamWriter with a BufferedReader Refer the example functi… Read More
  • Using Regular Expression in JavaThis article provides an introduction to usage of regular expressions in Java with some examples. Regular Expression or Regex in the computing terms … Read More
  • Thread Pools in JavaIn this article, we will explore the concept of thread pools in Java with examples. To scale applications it becomes necessary to separate thread crea… Read More
  • Approaches to read files in JavaThis article describes some of the common approaches to read files in Java. Using InputStreamReader with a BufferedReader Refer the example function… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Follow @StackStalk
Get new posts by email:
Powered by follow.it

Popular Posts

  • Python FastAPI file upload and download
    In this article, we will look at an example of how to implement a file upload and download API in a Python FastAPI microservice. Example bel...
  • Avro Producer and Consumer with Python using Confluent Kafka
    In this article, we will understand Avro a popular data serialization format in streaming data applications and develop a simple Avro Produc...
  • Monitor Spring Boot App with Micrometer and Prometheus
    Modern distributed applications typically have multiple microservices working together. Ability to monitor and manage aspects like health, m...
  • Server-Sent Events with Spring WebFlux
    In this article we will review the concepts of server-sent events and work on an example using WebFlux. Before getting into this article it ...
  • Accessing the Kubernetes API
    In this article, we will explore the steps required to access the Kubernetes API and overcome common challenges. All operations and communic...
  • Python FastAPI microservice with Okta and OPA
    Authentication (AuthN) and Authorization (AuthZ) is a common challenge when developing microservices. In this article, we will explore how t...
  • Scheduling jobs in Python
    When developing applications and microservices we run into scenarios where there is a need to run scheduled tasks. Examples include performi...
  • Using Tekton to deploy KNative services
    Tekton is a popular open-source framework for building continuous delivery pipelines. Tekton provides a declarative way to define pipelines ...

Copyright © 2025 StackStalk