• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Exception » Redirecting and Rethrowing Exceptions in Java
Next →
← Prev

Redirecting and Rethrowing Exceptions in Java

By Dinesh Thakur

We’ll be covering the following topics in this tutorial:

  • Redirecting exceptions using throws
  • Rethrowing an exception

Redirecting exceptions using throws

Recall that the code capable of throwing an exception is kept in the try block and the exceptions are caught in the catch block. When there is no appropriate catch block to handle the (checked) exception that was thrown by an object, the compiler does not compile the program. To overcome this, Java allows the programmer to redirect exceptions that have been raised up the call stack, by using the keyword throws. Thus, an exception thrown by a method can be handled either in the method itself or passed to a different method in the call stack.

To pass exceptions up to the call stack, the method must be declared with a throws clause.

All the exceptions thrown by a method can be declared with a single throws clause; the clause consists of the keyword throws followed by a comma-separated list of all the exceptions, as shown below:

Void RedirectExMethod( ) throws Exception_A, Exception B, Exception C {
}

Program illustrates two methods redirecting an exception Exception from the method

throwing it, that is, ConvertAndDivide, to the calling method, main.

Program Redirecting exceptions.

public class Divide {
 public static void main(String[] args) {
   System.out.println("\n Program Execution starts here\n");
   try {
     convertAndDivide ( args[0],args[1]);
   }
   catch(Exception e) {
     System.out.println (e.getMessage () +"\n");
     e.printStackTrace ();
   }
    System.out.println("\n Program Execution Completes here");
 }
    static void convertAndDivide (String s 1,String s2) throwsException {
      int a, b, c;
      a = Integer.parselnt (s1);
      b = Integer.parselnt (s2);
      c = divide (a, b);
      System.out.println( a + "/" + b + "=" + C );
 }
     static int divide(int x, int y) throws Exception {
     if (y==0) {
       throw new Exception("Second Argument is Zero ...");
     }
      return x/y;
  }
}

The output of Program is the following:

C:\javatest>java Divide 4 0

 

Program Execution starts here

Second Argument is Zero …

Program Execution Completes here

C:\javatest>java Divide 4 a

Program Execution starts here a

java.lang.NumberFormatException: a
at java.lang.lnteger.parse Int (1nteger.java:426)
at java.lang.lnteger.parsel Int (1ntege r.java:476)
at Divide.convertAndDivide (Divide.java:26)
at Divide.main (Divide,java:9)

Program Execution Completes here

C:\javatest

The method getMessage() in Program just prints the message that is given at the time of the throw statement. If no message is given, then the data value that is responsible for the exception is shown; printStackTrace() prints the all the names of the methods that are called in generating the exception. The method names are printed in the reverse order of their call.

While defining exception handlers, it is instructive to take into account the scope of a method. The scope of the exception-handling mechanism is not limited to the exceptions that can be thrown by the code written into the method; it extends to the methods that called the method in which the exception is thrown. That is, the scope also includes exceptions thrown by methods called by that method and so on.

Rethrowing an exception

An exception that is caught in the try block can be thrown once again and can be handled. The try block just above the rethrow statement will catch the rethrown object. If there is no try block just above the rethrow statement then the method containing the rethrow statement handles it. To propagate an exception, the catch block can choose to rethrow the exception by using the throw statement. Note that there is no special syntax for rethrowing. Program illustrates how an exception can be rethrown .

Program Rethrowing exceptions.

public class Divide {
 public static void main(String[] args) {
   int a, b, c;
   try {
      a = Integer.parselnt (args [0]);
      b = Integer.parselnt (args [l]);
      try {
        c = a/b;
        System.out.println ( a + "I" + b + "=" + c);
      }
      catch (ArithmeticException e) {
        System.out.println ("Second Argument Should not be Zero");
        System.out.println ("Rethrowing the object again");
        throw e;
      }
   }
 { System.out.println("Arguments passed should be valid Numbers"); }
   catch(ArraylndexOutOfBoundsException e)
 { System.out.println(Pass Proper Arguments"); }
   System.out.println("\n Program Execution Completes here");
 }
}

Often first-time readers may get confused about the use of the three keywords: throw, throws and Throwable. It is therefore useful to dwell on the three concepts together in order to clarify their meaning.

Throwable is a class. Though the Throwable class is derived from the java.lang.Object class in the Java class library, Throwable is the super-class of all classes that handle exceptions.

The keyword throw is a statement that throws an exception. Note that an exception can be thrown either by the throw statement or when an error occurs during the execution of any other statement.

The keyword throws is a clause specified in the method definition which indicates that the method throws the exceptions mentioned after the keyword throws, which are handled in the called methods.

You’ll also like:

  1. Rethrowing Exceptions Java Example
  2. Exceptions – What is Exceptions? Type of Exceptions
  3. What are the causes of exceptions in java
  4. Chained Exceptions in Java Example
  5. Unchecked and Checked Exceptions
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW