Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between propagating and handling?

Tags:

java

exception

I'm studying for a CS exam this Friday and have hit a bump in the road here. The question asks me to handle the exception and then propagate the exception using two different methods, but I was under the impression they were the same thing. Can anyone help? The practice question is listed below.

You are given the following class:

public class ReadData {
   public void getInput() {
     getString();
     getInt();
   }

   public void getString() throws StringInputException {
     throw new StringInputException();
   }

   public void getInt() throws IntInputException {
     throw new IntInputException();
   }
}

class StringInputException extends Exception {}

class IntInputException extends Exception {}

The code above will result in compilation errors in getInput() method. Rewrite getInput() method using two different techniques:

Method 1 - Handle the exception 

Method 2 - Propagate the exception

so that the code compiles.

like image 382
Davis Avatar asked Jan 23 '26 10:01

Davis


2 Answers

They are not the same thing. Propagation basically means re-throwing the exception, that is, allowing somewhere further up in the code to handle it; generally this is done if nothing can be done about the exception at the current level. Handling the exception means catching it and actually doing something about it - informing the user, retrying, logging - but not allowing the exception to go any further.

like image 68
Yuushi Avatar answered Jan 24 '26 23:01

Yuushi


class Example {
    // a method that throws an exception
    private void doSomething() throws Exception {
        throw new Exception();
    }

    public void testHandling() {
        try {
            doSomething();
        } catch (Exception e) {
            // you caught the exception and you're handling it:
            System.out.println("A problem occurred."); // <- handling
            // if you wouldn't want to handle it, you would throw it again
        }
    }

    public void testPropagation1() throws Exception /* <- propagation */ {
        doSomething();
        // you're not catching the exception, you're ignoring it and giving it
        // further down the chain to someone else who can handle it
    }

    public void testPropagation2() throws Exception /* <- propagation */ {
        try {
            doSomething();
        } catch (Exception e) {
            throw e; // <- propagation
            // you are catching the exception, but you're not handling it,
            // you're giving it further down the chain to someone else who can
            // handle it
        }
    }
}
like image 29
rid Avatar answered Jan 24 '26 23:01

rid