I have the following java code:
if (ps.executeUpdate() != 1)
{
// Error - did not insert one row
String err = "insert unable to insert LocalUsage data: " + usg.toString();
Logger.log(err, _MODULE_CLASS, Logger.DEBUG);
throw new DaoException(err);
}
The problem if the query had a foreign key exception, then it will be thrown but it will never get to inside the if. what should I do so that it will get inside the if and output the log I have?
The problem is that this if condition is inside a try catch block, and it is going to the catch and never enters to the if condition.
executeUpdate() might throw an SQLException, as is described in its API documentation. You might want to catch that exception.
int count;
try {
count = ps.executeUpdate();
} catch (SQLException e) {
throw new DaoException("Exception while executing update: " + e.getMessage());
}
if (count != 1) {
// ...
}
As the docs states executeUpdate() may throw an exception so your code flow will fail and you will not be able to do any processing afterwards incase your exception handling is not proper.
Which I think is happening in your code right now.
While doing database call I would suggest you do it like this:
int operationStatus;
try {
operationStatus = ps.executeUpdate();
} catch(SQLException exp) {
final String message = "SQL Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} catch(Exception exp) {
final String message = "Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} finally {
//you may wish to clean up resources if they are not going to be used after this point.
}
if(operationStatus < 0) {
//Next steps
}
Related
I have the following code running in my project:
HashMap<String, DeviceData> deviceMap = getAllDevices();
int status = 0;
DeviceHandle devHandle = null;
for (LicenseData licenseData:listLicenses) {
Map<String, String> licenseMap = licenseData.getLicenseKeyValues();
if ((licenseMap != null && !licenseMap.isEmpty())) {
String keyDecrypt = licenseMap.get("key");
Date expiryDate = new Date(Long.parseLong(licenseMap.get("expiryDate")));
boolean allowForeign = Boolean.parseBoolean(licenseMap.get("allowForeign"));
String ipDecrypt = licenseMap.get("ipAddress");
if (expiryDate.compareTo(new Date()) > 0 || keyDecrypt.equals(licenseData.getKey().getCurrentValueAsString()))
{
try {
DeviceData device = deviceMap.get(ipDecrypt);
devHandle = (DeviceHandle)device.getHandle();
if(device != null && devHandle != null) {
deviceMap.remove(ipDecrypt, device);
System.out.println("After deletion device map.");
System.out.println(deviceMap);
createUser(devHandle);
try {
if (allowForeign) {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statemnt
deleteUser(devHandle);
}
else {
Process pr = Runtime.getRuntime().exec(SomeOperation);
status = pr.waitFor();
if (status == 0)
//Debug Statement
else
//Error Debug Statement
deleteUser(devHandle);
}
} catch(Exception e) {
//Exception statement
deleteUser(devHandle);
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
Explanation: I have a list of licenses for my application in listLicenses. All the devices present in the server are in deviceMap. For each license, I am decrypting it and getting the values. If license for a device is present, I get a handle on that device and doing some operations.
The issue is:
If I am not able to get a handle on device(getHandle()), or if I am not able to create a user after getting the device handle(createUser()), an exception is thrown. These methods are very hierarchical, i.e I am calling them from here, they are in another class throwing own exceptions and for their operation, they call other methods.
If there are three devices in the map, and three licenses, and if for the first one I am not able to get a handle or create a user, device is removed from deviceMap but no further execution happens i.e. for the next two devices.
If exception occurs for on device, I want to continue the exception for other two devices. I tried using return but couldn't get it to work.
Please help.Also, please forgive for the syntax and if any mismatch is there in the code.
Make use of first try's catch block.
This is how I handled when I faced same kind of situation.
catch (Exception exp) {
if (exp instanceof NullPointerException) {
log.info"Invalid/ Inactive ");
} else if (exp instanceof NonUniqueResultException) {
log.info("Multiple records existed");
} else {
exp.printStackTrace();
errorMsgs.append("Unexpected Error Occured. Please contact Admin.");
}
}
I have a task to make a program that will add up all the valid integers in a file and to ignore anything that isn’t a valid int. I have to use Try and Catch.
File Numbers = new File("Numbers.txt");
Scanner readFile = null;
int i = 0;
int total= 0;
boolean success = false;
while(!success){
try {
readFile = new Scanner(Numbers);
while(readFile.hasNext()){
i = readFile.nextInt();
System.out.println(i);
total = i + total;
};
success = true;// Ends The loop
} catch (FileNotFoundException e1) {
System.err.println(Numbers.getName()+" does not exist");
}
catch(InputMismatchException e2){
System.err.println("Data incorrect type expecting an int found: " + readFile.nextLine());
readFile.next();
}
System.out.println("total is: " + total);
};
The problem is that the program gets caught in an infinite loop, where instead of going past the exception it just starts again.The task seems pretty straight forward, yet i don't know why it wont work?
You fall into infinite loop because when exception happens, the success variable didn't change its value to true. In order to do some action even when exception happens you should add the finnaly block. It could look like this:
try {
// do some stuff
} catch (Exception e) {
// catch the exception
} finally {
if (!readFile.hasNext()) success = true;
}
And by the way, never do this: catch (Exception e), I did it just for example sake. Instead always catch the specific exception. Because Exception is the most basic class in the exception hierarchy, so it will catch up all the exceptions, and unless you re-throw it you could have false feeling of "safiness". When you want to catch all the exceptions, you should do this:
try {
// do stuff
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
e.printStackTrace(); // or other approptiate action, i.e. log it.
}
Assume any of the following FileNotFound or InputMismatchException exceptions will raise, then your program wont change success to true. Thus it returns to the outer while loop and read the same file. Because nothing has changed the same Exception will be thrown again.
==> Endless loop.
To fix that I suggest to move the try/catch block to the inner while.
Ok here is my code fragment:
try
{
res = gfSQL.doSQL("SELECT TIMESTAMP, MSGLEVEL, APPLICATION, STREAM, THREADID, " +
" THREADNAME, REQUESTID, MESSAGE, ID, PROCESSED" +
" FROM GFLOG where PROCESSED = 'N'" +
" ORDER BY TIMESTAMP, ID");
} catch ( SQLException e) {
e.printStackTrace();
System.exit(128);
}
if (! res.first()) { <<<---- FLAGGED STATEMENT
// no data to process
System.err.println("No data found to process\n");
return;
}
Now java is flagging the indicating statement (and just about everyone after it) with a 'Unhandled exception type SQLException). gfSQL.doSQL throws this exception and is defined with:
public ResultSet doSQL(String sqlCommand) throws SQLException
{
The funny thing is - if I repeat the 'catch' block like so:
try
{
res = gfSQL.doSQL("SELECT TIMESTAMP, MSGLEVEL, APPLICATION, STREAM, THREADID, " +
" THREADNAME, REQUESTID, MESSAGE, ID, PROCESSED" +
" FROM GFLOG where PROCESSED = 'N'" +
" ORDER BY TIMESTAMP, ID");
} catch ( SQLException e) {
e.printStackTrace();
System.exit(128);
} catch ( SQLException e) {
e.printStackTrace();
System.exit(128);
}
if (! res.first()) {
// no data to process
No 'unhandled' error is flagged. (however the duplicate catch phrase is flagged as an 'unreachable catch block - SQLException is already handled' of course.)
Any ideas why Java sees the catch in one instance but not the other? Or am I missing something?
Well, gfSQL.doSQL()can throw a SQLException, and you're catching it.
But res.first()can also throw a SQLException, and you're not catching it, since this instruction is out of the try block. That's why you get the compiler error.
res.first() should be in the try block as it can throw an exception:
try {
res = // ...
if(!res.first()) {
// ...
}
} catch ( SQLException e) {
// ...
}
I am encountering an error when user doesn't type anything into input statement. I thought of using Try/Catch blocks to instead throw exception to set boolAskRepeat to true which should skip to the end of the code and repeat the loop.
This doesn't work, and I believe I'm missing something but I'm not sure what... It still throws exception saying:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at ITSLab03.main(ITSLab03.java:34)
Which is this line of code: inputStatus = input.readLine().toLowerCase().charAt(0);
What am I doing wrong here?
while (boolAskStatus == true)
{
System.out.print("Employment Status (F or P): ");
try
{
inputStatus = input.readLine().toLowerCase().charAt(0);
if (inputStatus == "f".charAt(0))
{
boolAskStatus = false;
String stringCheckSalary = null;
boolean boolCheckSalary = true;
while (boolCheckSalary == true)
{
// some code
}
outputData(inputName, inputStatus, calculateFullTimePay(inputSalary));
}
else if (inputStatus == "p".charAt(0))
{
// some code
outputData(inputName, inputStatus, calculatePartTimePay(inputRate, inputHours));
}
else boolAskStatus = true;
}
catch (IOException e) { boolAskStatus = true; }
}
You need to catch StringIndexOutOfBoundsException as well (If you observe the stack trace properly this is the exception you are getting)
catch (StringIndexOutOfBoundsException e) {
boolAskStatus = true;
}
(or)
catch Exception which catches all runtime exceptions
catch (Exception e) {
boolAskStatus = true;
}
The normal try catch pattern should look like this:
try
{
// code that is vulnerable to crash
}
catch (Specific-Exception1 e1)
{
// perform action pertaining to this exception
}
catch (Specific-Exception2 e2)
{
// perform action pertaining to this exception
}
....
....
catch (Exception exp) // general exception, all exceptions will be caught
{
// Handle general exceptions. Normally i would end the program or
// inform the user that something unexpected occurred.
}
By using .charAt(0), you are assuming that the String has a length > 0.
You could simplify this a bunch by just doing:
String entry = input.readLine().toLowerCase();
if (entry.startsWith("f")) {
...
}
else if ("entry".startsWith("p")) {
...
}
Your code doesn't work the way you want because input.readLine().toLowerCase().charAt(0) throws a StringIndexOutOfBoundsException, which is not an IOException, so the catch block never gets hit. You can make it work by changing the catch to
catch (StringIndexOutOfBoundsExceptione e) { boolAskStatus = true; }
But...
It's generally not a good idea to base your program's normal behaviour on exception handling. Think of exception throwing as something that could happen, but usually won't. Why not use something like:
final String STATUS_F = "f";
final String STATUS_P = "p";
String fromUser = null;
do {
String rawInput = input.readLine().toLowerCase();
if (rawInput.startsWith(STATUS_F)) {
fromUser = STATUS_F;
} else if (rawInput.startsWith(STATUS_P)) {
fromUser = STATUS_P;
}
} while (fromUser == null);
if (STATUS_F.equals(fromUser)) {
// do something
} else if (STATUS_P.equals(fromUser)) {
// do something else
} else {
// Shouldn't be able to get here!
throw new Exception("WTF!?");
}
It much easier for another person reading this to understand why the program loops and how the loop is controlled, in part because the code that figures out what the user is inputting and the code that decides what to do with that information are separated. Plus, you don't need to deal with exceptions.
I have this line of Code
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {
}
It is possible, that only one of the three properties are set. But if one property isnt set, I get this NullpointerException. I catch it, but then the try-Block isnt continued.
So e.g. if the article.getTxtText() method returns null, I dont get the txtLongText and txtShortText Strings either, although at least one of them has a not empty String set.
So the question is, how can I continue the try-block although there's is an Exception caught?
Thanks a lot.
You should either use 3 try-catch blocks or just use a null-check around every case.
if (article.getTxtText() != null) {
// do part 1
}
if (article.getObjLongTextData() != null) {
// do part 2
}
I would imagine that the correct approach to this is to have three try/catch blocks around each point of code. The whole point of a try block is that you are trying the code as a lump and if it fails anywhere you abandon it. For what you are describing you would need three try/catches around each possible point of failure.
That having been said you are probably better off testing for null rather than relying on exception handling to do that. Exception handling should be for exceptionalm unforeseen events, not for flow control in a program.
If you must do this with exceptions (and I don't think you should), then you need to have 3 separate try/catch blocks:
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
} catch (NullPointerException e) {}
try {
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
} catch (NullPointerException e) {}
try {
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {}
Once an exception is thrown in your code you cannot restart execution in the middle of the try block.
Having said that I would always prefer to detect the null pointer with an if test rather than relying on exception handling for this non-exceptional condition.
do defensive programming ,check for nulls.
if ( variable != null ){
...
}
The simplest and better approach from my point of view would be break the try - catch block in three different try-catch block, something like the following :
try {
String txtText = article.getTxtText().toString();
if (StringUtils.hasText(article.getTxtText().toString())){
textPropertyList.add(txtText);
}
} catch (NullPointerException e) {
//Handle Exception
}
try {
String txtLongText = article.getObjLongTextData().toString();
if (StringUtils.hasText(txtLongText)){
textPropertyList.add(txtLongText);
}
} catch (NullPointerException e) {
//Handle Exception
}
try {
String txtShortText = article.getObjShortTeaserData().toString();
if (StringUtils.hasText(txtShortText)) {
textPropertyList.add(txtShortText);
}
} catch (NullPointerException e) {
//Handle Exception
}
I'd recommend a different design:
private void addProperty(Object property, Collection<String> properties) {
if (property == null) {
return;
}
String textProperty = property.toString();
if (StringUtils.hasText()) {
properties.add(textProperty);
}
}
Usage:
addProperty(article.getTxtText());
// ...
Why are you doing this in a try / catch, just use simple if
if ( txtText != null ){
...
}
if ( txtLongText != null ){
...
}