catch with if and else

gudii9
gudii9 used Ask the Experts™
on
try{
			
			previouslyTaken = new DataDAO().testForPkgPreviouslyTaken(this....., TimeStamp);//gives true or false boolean value
		}
		catch (XYZExceptionException xyze)
		{
			if(xyze.getMessage().contains("999"))
			{
				LOGGER.error("item is PreviouslyTaken due to aa", xyze);
				errorCodes.add(XYZConstants.PREVIOUS_TAKEN_EXISTS);				
			}
			else if(xyze.getMessage().contains("888"))
			{
				LOGGER.error("item is PreviouslyDumped due to bb", xyze);
				errorCodes.add(XYZConstants.PREVIOUSLY_DUMPED);
			}
			else
			{
				throw new XYZException(xyze);
			}	
			return ;
		}
		LOGGER.info("previouslyTaken indicator from DB {}",previouslyTaken); //coming false t me
		
		if(!previouslyTaken){
		processIt();
		else
		LOGGER.info("item taken or dumped so update status to new)

Open in new window


i have above code in a method.

i never saw if else inside a catch in earlier.

why some one use if else inside catch
when the catch is thrown as try block simply return true or false

when it has 999 or 888 etc value in the xyze exception

please advise
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Chief Technology Ninja
Distinguished Expert 2018
Commented:
Hi gudii9,

when the catch is thrown as try block simply return true or false

Nopes. That is incorrect. While Try...Catch is a special block to handle exceptions, it does not return anything. It is just another code block like if...else and it is possible to nest it within other code blocks and vice versa.

And as per the above code block, it is just determining what information should be logged basis the error message.

Please refer to: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch

Regards,
Chinmay.
Kyle AbrahamsSenior .Net Developer
Commented:
Essentially they're evaluating the error message.

A perfect example of this is web:
Try 
{
  BrowsePage();
}
Catch (exception ex)
{
   if (ex.Message == "404")
         return "Not Found";
   else if (ex.Message == "401")
         return "Not Authorized";
   else 
        throw new exception (ex);  // this error isn't handled, so throw it up to the calling application.
}

Open in new window

Author

Commented:
BrowsePage();

in my case
previouslyTaken = new DataDAO().testForPkgPreviouslyTaken(this....., TimeStamp);

above DAO calls below method
testForPkgPreviouslyTaken()
which calls below stored procedure
ABC_Upd(?,?,?)
finally

previouslyTaken is assigned with either true or false value
So my basic question is there is no scenario the code enters Catch block right if try block is always either true or false


log message from log server for below line printed false to confirm my assumption
LOGGER.info("previouslyTaken indicator from DB {}",previouslyTaken); // showing false in log server
Ensure you’re charging the right price for your IT

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden using our free interactive tool and use it to determine the right price for your IT services. Start calculating Now!

Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
So my basic question is there is no scenario the code enters Catch block right if try block is always either true or false

If there is an error thrown by the code(For example, if your Stored Procedure failed) or any other exception for that matter,
previouslyTaken = new DataDAO().testForPkgPreviouslyTaken(this....., TimeStamp);

Open in new window

previouslyTaken will only have the value which was set at the time you declared the variable and execution will enter the catch block.
I think someone has given you a wrong idea about how Try...Catch works.

Author

Commented:
public class XYZException extends Exception {

	private static final long serialVersionUID = -3552076021567777777L;
	
	public XYZException(Exception exception) {
		super(exception);
	}
	
	public XYZException(String message) {
		super(message);
	}
	
	public XYZException() {
		super();
	}

}

Open in new window

XYZException class has above code
It is custome exception class right

why we need above kind of custom class instead of using just generic Exception

instead of below
catch (XYZException xyze)
		{
			if(xyze.getMessage().contains("999"))
			{

Open in new window


below is better right?
catch (Exception xyze)
		{
			if(xyze.getMessage().contains("999"))
			{

Open in new window

Kyle AbrahamsSenior .Net Developer

Commented:
Need to see the definition of super.
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
Well... we are going in different direction from your question here but then it is a really interesting point to discuss.
It is always recommended that you throw specific the exception. The caller doesn't know your code and might have to handle the exception. The more information you can provide about your code, is better. For example, consider this pseudo-code
Try
{
CallDatabase();
ReadFile();
TransmitOnNetwork();
}
catch(Exception exception)
{
// Handle the exception
}

Open in new window


When the above Try block fails, in catch block how will you take corrective measures OR if it is not possible to recover, the cleanup measures and gracefully exit your app? Instead of looking for specific string, wouldn't it be better to catch specific exception? For example, a FileNotFound Exception will tell us the file was not found, you could actually ask your user to locate the file themselves and restart this method.

Also, most of the IDEs provide you with the information about a method that you are going to call, what kind of exceptions it might throw, makes it easier for the developer to understand the method in a better way and tells them how to call the method - keeping in mind the exceptions, and plan accordingly. They might be able to write code so that, that exception is never occurred for example, they can check if the file exists before ReadFile() is called.

I hope this will clarify your doubts on custom exception.

Author

Commented:
When the above Try block fails, in catch block how will you take corrective measures OR if it is not possible to recover, the cleanup measures and gracefully exit your app? Instead of looking for specific string, wouldn't it be better to catch specific exception? For example, a FileNotFound Exception will tell us the file was not found, you could actually ask your user to locate the file themselves and restart this method.
i got multiple catch part

what i have not got is having one catch with if and else if and else loop inside that as below



catch (XYZExceptionException xyze)
		{
			if(xyze.getMessage().contains("999"))
			{
				LOGGER.error("item is PreviouslyTaken due to aa", xyze);
				errorCodes.add(XYZConstants.PREVIOUS_TAKEN_EXISTS);				
			}
			else if(xyze.getMessage().contains("888"))
			{
				LOGGER.error("item is PreviouslyDumped due to bb", xyze);
				errorCodes.add(XYZConstants.PREVIOUSLY_DUMPED);
			}
			else
			{
				throw new XYZException(xyze);
			}	
			return ;
		}

Open in new window

Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
The original code must be throwing the error message with specific error codes as part of the body. And the implementer of the above code might have decided that S/He does not want to handle it via specific exception hierarchy but wants to handle it using simple if...else. While it works(and I think up to an extent it is ok to use), personally I would have implemented it differently.

I would use Error codes instead of getMessage() I would use getErrorCode() and do the if...else as necessary. Also, if I am implementing a really complex system, I would go with exception hierarchy + errro code based if..else.

Also, in above code block is trying to evaluate the exception and if a known exception is not found(and therefore, is not logged/handled) it throws a new exception encapsulating the original exception as an inner exception.

And as mentioned earlier, Try...Catch... are just like other code blocks, there is nothing wrong in putting them inside each other - as long as they are syntactically correct.

Author

Commented:
testForPkgPreviouslyTaken() throws XYZException{
----
----

} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			rollBack(connection, callableStatement, null);
			throw new XYZException(e);
		} finally {
			closeCallableStatement(callableStatement);
			closeConnection(connection);
		}
return ispreviouslyTaken ;
}

Open in new window


i see above method implementation
it has catch block catching custom exception and it also has throws clause

i feel lot of code is redundant relating to exceptions here?

any good training videos on these topic to clearly understand these intricate concepts

my mind works well with video books with code examples rather than text books
please advise
Chinmay PatelChief Technology Ninja
Distinguished Expert 2018

Commented:
i feel lot of code is redundant relating to exceptions here?

Not in the above code block, It is simply handling an exception and logging the necessary details. It is throwing the exception back, but that is something I can't comment without looking into the caller and then finally block is cleaning up. Looks alright to me.

I am sorry with Java I am not sure which video training is better and why. The answers I provided to you are universal truths and I think beyond the programming languages itself. I think you will have to consult a Java expert to get that answer. You may want to make couple of quick searches as well.
To the OP: Except for the habit of catch -> log-> rethrow there's nothing wrong with the implementations you've shared. What you're getting down to is developer's choice and in this case it's simply not what you have chosen.
  • In both scenarios the exception is being interrogated, logged and then rethrown to possibly be handled further back up the stream. In the .NET world the best practice would be to either take specific action in the catch() [such as log and continue processing without notifying the caller about the exception] -- OR -- getting rid of the catch() entirely and let the exception bubble back up as high as possible so that the call stack is preserved. At the end of the day, you should do whatever your team's standard is. Note that making such a move might prove to be a MUCH larger refactoring than you're expecting.
  • Custom Exceptions are generally favored over the generic Exception because they can be specifically caught without having to dissect the exception and guess at what caused the issue. Again, you can look for that specific scenario superset and let everything else automatically bubble back up the stack.

A good place to start looking for tutorials is this search: java exception handling best practices

Good luck!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial