Why do we need the throw keyword in Java? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
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:
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)
In the given example, why did the user choose to throw an exception instead of simply printing the error?

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.

I think following answer can help you to understand ....
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.
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";

'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).

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.

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));
}

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.

Related

Is executing code inside of an exception bad in this case?

I have this specific scenario:
my exceptions have a code and a localized message
The thrower just knows the code
The catcher expects a localized message
The localization is inside of a DB table
Would it be wrong something like this:
public class MyException{
public MyException(int code){
try{
this.message = db.selectMessage(code);
}catch(Exception ex){
this.message = "";
}
}
}
This would completely hide from the thrower the fact that the message is localized.
Alternatively I should go with something like this:
public class ExceptionUtils{
public static throwMyException(int code) throws MyException{
String message = db.selectMessage(code);
throw new MyException(code, message);
}
}
But this requires the thrower to know about this util.
I would suggest using ResourceBundle class as it is widely accepted way for localization. This way you store your messages in files as oppose to DB. Also reading your messages from those files is handled by JVM and you don't have to write your own code for it. However, if you insist on using DB, I would sudgest to read all your messages from DB into file system or onto your memory during your app initialization and then you don't have to read from DB and risk DB connectivity failure for each exception.
This is a better approach:
public class MyException extends Exception {
private int code;
public MyException(String message, int code) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}
Usage:
Integer messageCode = null;
try {
// do stuff
} catch (MyException e) {
logger.log(e.getMessage(), e); // log actual message
messageCode = e.getCode();
}
if(messageCode != null /* && you really want to show it to end user */) {
String localizedMessage = db.selectMessage(code);
// show localized message to end user
}
Adavantages:
You don't need a Util class to throw exceptions.
You don't need to access db every time you throw an exception but
only when you catch it and "decide" to fetch the message if you want
to show it to user.
You don't need to catch an exception inside another exception.
You don't lose the actual non-localized message.
You don't lose actual stack trace in case db.getMessage() fails and throws exception.
Edit:
There is a dispute about whether the if part is a good idea or not so I have to elaborate.
message and localized version of message, these are very different.
Message:
is a description of what has gone wrong.
is what you see in console and in log records when exception occurs.
is in English.
must be shown regardless of any conditions and if not shown it's considered a very bad practice.
Localized Message:
is a translation of Message for the benefit of End User and not programmer.
is not in English.
is not expected to be shown either in console or log records.
is only needed when interacting with End User in UI.
is not expected to be used in non-UI related parts of code.
In the actual code provided by asker, message is replaced by localized message which violates expected behavior of a well-designed exception so I separated these two. In my code the message is Always shown and can be logged whenever exception occurs regardless of any conditions; Fetching localized message occurs only IF you actually need to interact with End Users. So access to DB can be skipped when you are not interacting with them.
the catch block is designed to do some actions after an exception occurs in your program, hence i would recommend you to provide some of the exception handling code in the catch block as it will allow others to understand your program efficiently
It is not bad as long it is code that helps you best handle the exception
The problem is one of too many moving parts. If your database access within the catch block fails by throwing an exception - and it can fail for any one of a number of reasons - then you won't ever see even your original exception. The same goes for anything you do in the catch block that could itself throw an exception.
This has recently happened to me, in fact, in legacy code (different language though same idea). Man is that a pain when you know your production system is failing for some specific reason but you have no idea what that specific reason is ...
It may be the case that your routine db.selectMessage() is itself protected against and won't throw an exception. Ok then. But it's going to be your responsibility to check that in every catch block you write. It's better to go with a design approach that doesn't involve catch blocks that do much of anything except things known to be 'safe'.
In some languages, by the way, catching all exceptions catches some really nasty ones (in Java, those aren't usually subclasses of java.lang.Exception though). And sometimes you really don't want to do anything unnecessary, 'cause you don't know what state you're in and what'll happen.
In this case, you're probably going to be logging that exception somewhere (or otherwise notifying the user). That logging code is (or should be) centralized in your application. That's the place to carefully translate/localize/interpret the exception code ... someplace where in one place you can make sure it works and is protected ... same as the logging code itself.

IText Constructor not Throwing Exception or Following Flow

I have a static method used to get the title from a PDF using the metadata via itext, which is used as a small part of a major Task.
I noticed an inexplicable path that I narrowed down to this section of code. Specifically, in the line where I instantiate a PdfReader, the process doesn't throw an exception or continue through to the print statement. In fact, it clears out all of my for loops up to the top level of my program and acts as if nothing has happened and my task completed.
try {
System.out.println("Entered method");
PdfReader myReader = new PdfReader(file.getAbsolutePath());
System.out.println("Reader instantiated"); //if no issues, prints to console
Map<String, String> info = myReader.getInfo();
System.out.println(info.get("Title"));
return info.get("Title");
} catch (IOException e) {
System.out.println("PdfReader throws exception"); //if issues, prints to console
e.printStackTrace();
}
Unless I'm mistaken, when this set of code is executed in my method, either "Reader Instantiated" or "PdfReader throws exception" is printed out to the console.
Neither happens. Instead, the process skips every if/for/while loop it is currently in and ends the task.
I'm wondering if someone can explain to me what is happening and how I should go about fixing it?
In the odd event this is searched for, yes, catching Throwable stops the thread from bailing out. I had never seen something like this before. The cause behind the problem was that a PDF was password-protected, so getInfo() failed.

Handling exceptions in Java (GWT)

I'm currently dealing with exceptions handling and I'm wondering where should I catch them.
Here is an stack from the GWT app :
A helper with a method which can throws NumerFormatExeption
(FormHelper.java)
A widget which uses this helper (CostWidget.java)
A presenter which calls this widget to retrieve data (BuildingPresenter.java)
FormHelper.java
public static Integer prepareIntegerForDb(String string) {
return Integer.parseInt(string);
}
CostWidget.java
public DetailCostProxy getCostDetail() {
...
costDetail.setQuantity(FormHelper.prepareDoubleForBd(qtTextBox.getText()));
...
return costDetail;
}
public List<DetailCostProxy> getCostList() {
...
costDetails .add(ligneCout.getCostDetail());
...
}
BuildingPresenter.java
public void saveBuilding(final BuildingProxy inter, final CollectRequestContext savecontext) {
savecontext.save(display.getCostWidget().getCoutList()).fire(new Receiver<BuildingProxy >() {....
}
I am thinking about :
1) adding "throws NumberFormatException" to prepareIntegerForDb() in the helper
2) adding "throws NumberFormatException" to getCostDetail() in the widget
3) adding "throws NumberFormatException" to getCostList() in the widget
4) caching the exception in the presenter (in saveBuilding)
The aim is :
to log the exception
to provide the user with a message saying that something went wrong
What do you think about this approach considering that this in an example and I will have to apply this pattern into the entire app (more than 20 presenters).
Is my way a good way to handle exceptions in GWT ? or should I log the error directly in the helper or elsewhere ?
prepareIntegerForDB() should throw the exception. This happens automatically when Integer.parse() fails, and you do not have to actually throw the Exception.
getCostDetail() should explicitly catch and throw the exception, and possibly expand upon why it was thrown. Something like "The cost was not in a readable format". That method is responsible for only that one line.
getCostList() should catch and handle the exceptions. That method is responsible for an entire collection. If you do not handle the bad data here, you will lose the good data. Here is one way to handle the bad data.
public List<DetailCostProxy> getCostList() {
...
try {
DetailCostProxy cost = lineCount.getCostDetail()
costDetails.add(cost);
catch (NumberFormatException e) {
costDetails.add(null);
}
...
}
Finally, the method that displays your data to the user should interpret the data passed to it before displaying it. If you used my example above, this would be as simple as checking for null values.
What do you think about this approach considering that this in an
example and I will have to apply this pattern into the entire app
(more than 20 presenters).
Adding throws NumberFormatException declarations won't help you to "provide the user with a message saying that something went wrong". NumberFormatException-s are RuntimeException-s so the throws declaration won't even force to try/catch in the code that uses these methods.
Is my way a good way to handle exceptions in GWT ? or should I log the
error directly in the helper or elsewhere ?
4) catching the exception in the presenter (in saveBuilding)
The aim is :
to log the exception
to provide the user with a message saying that something went wrong
This question is not specific to GWT.
To catch the Exception is a good idea if you know how to deal with it.
If you signal the error to the user, you need to be able to have the user decide how to handle the issue (for example a pop-up message proposing two actions to resume the application execution).

Is there a way for one method to resolve itself before moving on to the next item in code

I have searched this site, oracle, and others to no avail.
I am having a couple of issues with my program, but for right now I only want to deal with one.
First let me post the parts of my program I am having issues with
verifyAge method
private void verifyAge()
{
String ca = iP.cAge.getText();
try
{
a = Integer.parseInt(ca);
if (a < 0 || a > 120)
{
JOptionPane.showMessageDialog(null,"Enter number between 0"
+ " and 120", "Input Error",JOptionPane.ERROR_MESSAGE);
iP.cAge.setText("");
}
}
catch(NumberFormatException afe)
{
JOptionPane.showMessageDialog(null, "Must Enter Number", "Input"
+ " Error", JOptionPane.ERROR_MESSAGE);
iP.cAge.setText("");
}
}
I have a FileListener that this code will be going into. It needs to run and loop until error is fixed before moving on in the code. Does anyone have any suggestions and please give examples.
You have two choices to achieve this:
Either return a value from your validate methods and check the value in acitonPerformed. If validated then only move to the next method. You can achieve this by putting few if/else statements
Or you can create validate exception classes. If your validate method is not able to validate then it should throw an exception which you can catch in your action performed. If you put all the validate method in the try block then if a method throws the exception you can skip other methods as you reach the catch block.
I am not sure whether I correctly understand your second problem. As I understand you want to continue with the program even if your addFile method throws an exception. For that case you need to wrap your addFile method call in a separate try catch. You need not to return from your actionPerformed in case of exception if your program can logically continue with addfile failure. Simply log an error in the catch that addFile failed and continue with rest of the code following the catch statement.
Firstly, create a new Exception called something like ValidationException. Have each of the methods throw this. You will now be required to catch it in the ActionListener. This way, you stop all the other methods from executing when one fails.
Secondly, you need some way to either highlight or focus the field that failed.
You could use something like a Component called (for example) invalidField. If this is not null (in the actionPerformed method), you could call requestFocusInWindow to return focus control back to that field.
Each validation method would be required to set this before they threw their ValidationException

Java coding practice, runtime exceptions and this scenario

In the following scenario, I was trying to see how to handle this code and it how it relates to Runtimexception. I have read that is generally better to throw runtime exceptions as opposed to rely on static exceptions. And maybe even better to catch a static checked exception and throw an unchecked exception.
Are there any scenarios where it is OK to catch a static exception, possibly the catch-all Exception and just handle the exception. Possibly log an error message and continue on.
In the code below, in the execute1 method and execute2 method, let us say there is volatile code, do you catch the static exception and then rethrow? Or possibly if there are other errors:
if (null == someObj) { throw new RuntimeException(); }
Is this an approach you use?
Pseudo Code:
public class SomeWorkerObject {
private String field1 = "";
private String field2 = "";
public setField1() { }
public setField2() { }
// Do I throw runtime exception here?
public execute1() {
try {
// Do something with field 1
// Do something with field 2
} catch(SomeException) {
throw new RuntimeException();
}
}
// Do I throw runtime exception here?
public execute2() {
try {
// Do something with field 1
// Do something with field 2
} catch(SomeException) {
throw new RuntimeException();
}
}
}
public class TheWeb {
public void processWebRequest() {
SomeWorkerObject obj = new SomeWorkerObject();
obj.setField1("something");
obj.setField2("something");
obj.execute1();
obj.execute2();
// Possibility that runtime exception thrown?
doSomethingWith(obj);
}
}
I have a couple of problems with this code. There are times when I don't want a runtimeexception to be thrown because then execution stops in the calling method. It seems if I trap the errors in the method, maybe I can continue. But I will know if I can continue later on the program.
In the example above, what if obj.execute1() throws a Runtimeexception, then the code exits?
Edited: This guy seems to answer a lot of my questions, but I still want to hear your opinions.
http://misko.hevery.com/2009/09/16/checked-exceptions-i-love-you-but-you-have-to-go/
"Checked exceptions force me to write catch blocks which are meaningless: more code, harder to read, and higher chance that I will mess up the rethrow logic and eat the exception."
When catching an exception and throwing RuntimeException instead, it is important to set the original exception as a cause for the RuntimeException. i.e.
throw new RuntimeException(originalException).
Otherwise you will not know what was the problem in the first place.
Rethrowing checked exceptions as unchecked exceptions should only be done if you are sure that the checked exception is not to be expected.
Here's a typical example:
try {
hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
} catch (NoSuchAlgorithmException e) {
// Unexpected exception. "MD5" is just hardcoded and supported.
throw new RuntimeException("MD5 should be supported?", e);
} catch (UnsupportedEncodingException e) {
// Unexpected exception. "UTF-8" is just hardcoded and supported.
throw new RuntimeException("UTF-8 should be supported?", e);
}
There are times when I don't want a
runtimeexception to be thrown because
then execution stops in the calling
method. It seems if I trap the errors
in the method, maybe I can continue.
But I will know if I can continue
later on the program.
You have the right idea. The advice about throwing RuntimeException is that it doesn't require the caller to use a try-block or a 'throws' clause.
If your code can recover from an exception than it really should catch it and not throw anything.
One of the first rules about exceptions is to not abuse them to pass state in your application. They should be used for exceptional situations, not as alternative return values.
The second rule is to catch exceptions at the level you process them. Catch and rethrow does not add much. Any cleanup code in your method should be done in a finally block.
In my opinion catching checked exceptions and rethrowing them as runtime exceptions is abusing the system. It feels like working around the "limitations" of design by contract instead of using those "limitations" to get a more robust application.
Whether or not to handle an exception or simply rethrow it depends on your use case.
For example, if you're reading a file to load data into your application, and some IO error occurs, you're unlikely to recover from the error, so rethrowing the error to the top and consequently terminating the application isn't a bad course of action.
Conversely, if you're anticipating recoverable errors then you should absolutely catch and handle the errors. For example, you may have users entering data in a form. If they enter data incorrectly, your input processing code may throw an exception (e.g. NumberFormatException when parsing a malformed number string). Your code should catch these exceptions and return an error the user, prompting for correct input.
On an additional note, it's probably bad form to wrap all your exceptions with RuntimeException. If your code is going to be reused somewhere else, it is very helpful to have checked exceptions to signify that your code can fail in certain ways.
For example, assume your code is to parse configuration data from a file. Obviously, an IO error may occur, so you will have to catch an IOException somewhere in your code. You probably won't be able to do anything about the error, so you will have to rethrow it. However, someone calling into your code may well be able to handle such an error, for example by backing off to configuration defaults if the configuration can't be loaded from the file. By marking your API with checked exceptions, someone using your code can clearly see where an error may occur, and can thus write the error handling code at the appropriate place. If instead you simply throw a RuntimeException, the developer using your code won't be aware of possible errors until they creep up during testing.

Categories

Resources