0

In this answer, the code provided is:

void greet(String name) {
    if (name == null) {
        throw new IllegalArgumentException("Cannot greet null");
    }
    System.out.println("Hello, " + name);
}

I have seen similar examples on all sites where I went to learn the 'throw' keyword. What doesn't make sense to me whenever I see such examples is why would one simply not print: "Cannot greet null" instead of throwing an exception.

Questions:

  1. Are there better examples of the utility of the throw keyword? (I am just going to pass out of high school and know only high school level Java programming so please avoid complicated examples)

  2. In the given example, why did the user choose to throw an exception instead of simply printing the error?

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
Archer
  • 271
  • 5
  • 15
  • 2
    That depends on the *functionality* of the code. Nothing would be gained by just printing out *null* – Nicholas K Jan 12 '19 at 07:02
  • 3
    Like Nicholas said, print might be helpful in some debugging situations but throwing exceptions can help a program fail gracefully. Let's say you are working at the kitchen of a pizza parlor and you are told to make a pizza. Just as you get ready, you realize you have no dough. You can mutter "I have no dough" and continue on throwing sauce on the bare counter ("print"), or you can stop what you are doing and tell your manager you don't have dough ("throw/catch"). – BobtheMagicMoose Jan 12 '19 at 07:07
  • 1
    What if the code that's calling `greet` wants to know if there was a problem and ask again for another name? – chrylis -cautiouslyoptimistic- Jan 12 '19 at 07:18
  • @chrylis. It's a matter of opening stdout in w+ mode, and parsing the output :) – Mad Physicist Jan 12 '19 at 07:36

6 Answers6

4

Now it is time to revise the concept of Exception Handling in the Java.

First of All what is exception, whenever there is some error or say problem occur while executing the lines of code it is called the Exception.

For Example, If a person divides something with 0, then it will give an exception as computer cannot handle the undefined entity.

Another example will be while you have declared a Scanner in order to get in integer input, but user enters an alphabet so it will also cause the exception.

Here we do exception handling, which means that we will handle exception in such a way that it will not cause program to close, those specific line which have been enclosed in the try and catch statement will not work properly but other lines will executed.

Now if we have made a method that do something lets suppose prints a line, and there is an exception occurred while printing that line, here we can do two things handle that exception at place where it has occurred or throw it.

If we handle exception at that place it is okay, and if we throw it then we have to catch it place where we have called that method.

Now as there are two types of Exceptions 1) Run Time Exception Which We Call Unchecked Exception 2) Compile Time Exception Which We Call Checked Exception

Both exceptions can be handle at the class level and method level too, one more thing we can do chain exceptional handling too. Which means that one class will throw exception to other and so on.

1

I think following answer can help you to understand ....

  1. Are there better examples of the utility of the throw keyword?

Basically Throw and Throws are used to prevent the application for getting error or crashing by throwing exception. Throws are used in the method signature and Throw are used to prevent the flow from getting error. So here is a simple example for it.

    public class Test {

    // here we have used "throws" in method signature 
    //   because we are throwing new Exception(), if array is null
    public static int getValue(int[] array, int index) throws Exception {

        // here we are preventing application from getting 
        // unconditional error (NullPointer exception)
        // if array is null, then we are throwing new Exception()
        if(array == null) {
            throw new Exception();
        }

        int value = array[index]; 
        return value;
    }

    public static void main(String[] args) {
        int[] array = null;
        // here we are wrapping our getValue() function call to try catch block
        // because getValue() function can throws Exception
        // so we are making it safe to execute our program
        try {
            int value = getValue(array, 0);
            System.out.println("value " + value);
        } catch (Exception e) {
            System.out.println("Provided array is null... so we caught the exception...");
        }
    }
}

if you want to know more about how throw and throws works... then you need to know about Exception Handling (Checked and Unchecked) also.

  1. In the given example, why did the user choose to throw an exception instead of simply printing the error?

As per the given example, your function purpose is to greet, but if some other function call greet() with null value then there is no any reason to greet like Hello, null, so he throw an exception before executing the statement. like...

    void greet(String name) {
        System.out.println("Hello, " + name);
    }

    String myName = null;
    greet(myName); // it will print "Hello, null";
pramesh
  • 501
  • 3
  • 11
0

'Throw' keyword is used to notify the caller that the argument passed is not valid (in this case), or in general, something went wrong while executing the code called by the caller.

Consider an example where you are writing an online shopping application. Following would be the simple sequence of events:

  • User scrolls through items and selects one or more items
  • Items are added into the cart and user clicks check out
  • User is redirected to 3rd party's payment page where he types in card details and makes the payment
  • User is shown the success page

Now, during payment, if the card number is incorrect or user doesn't have enough balance in the card, would you throw the error back to the caller (i.e. shopping app) or just log it on the console (on payment provider's side) and return the response? Of course the former, so this is just to let the caller know that there is an error and he should handle it gracefully (by showing appropriate message on checkout in our case).

Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

A throw statement abruptly terminates the execution of the current function, and returns control right back to the caller, forcing them to deal with the error, or rethrow the exception up the chain.

An exception object contains lots of information about where and why an error occurred beyond just the error message. It keeps track of where in the call stack the error happened, and allows you to look up the sequence of calls that led up to it.

A print statement simply could not do all these things. Your example is already a good one. The job of the greet function is to print a greeting. If you pass in null, the function is unable to do so. Printing a message here would be potentially confusing. Instead, it forces you to deal with the fact that you have it invalid input rather than printing a benign message that someone might mistake for a greeting.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
0

Try Java 8 Optional:

String nullVal = null;
System.out.println(Optional.ofNullable(nullVal).orElseGet(() -> null));

String notNull = "Hello Optional";
System.out.println(Optional.ofNullable(notNull).orElseGet(() -> null));

The method can be modify like this:

public static void greet(String name) {
    System.out.println("Hello, " + Optional.ofNullable(name).orElseGet(()->null));
}

TongChen
  • 1,414
  • 1
  • 11
  • 21
0

Assume a function checks that in the passed directory is no malicious file. That could be a void method where you need to catch the exception for the rare case, bypassing the normal processing after the call.

try {
    checkDirectorySafe("/home/Donald");
    ... 
} catch (VirusException e) {
    ...
}

The catch might be late in the code and also catch exceptions in other parts.

There is an other advantage. The function can check all files in the directory and for all subdirectories need only recursively call itself with the subdirectory path. On an exception the call stack is unwound upto the catch.

The Alternative would be to have a boolean or Optional result, and add if code. If the function also needs to return some data, that could become slightly uglier.

An exception is like a toilet in a mall.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138