How to catch "Invalid hex digit"? - java

I have a program, in which a SQLException gets thrown:
java.sql.SQLException: Fail to convert to internal representation: Invalid hex digit
The error gets thrown in oracle.sql.RAW.hexString2Bytes, because the input data is invalid.
How can I catch this specific error without catching all other SQLExceptions?

You can get it by two method.
One is SQLException#getErrorCode() which will return an int, vendor-specific exception code for the SQLException object, and compare the int ( I don't know the exception code for "Invalid hex digit", but may be you can get this with System.out.println() )
And other method is you can get exception message by Throwable#getMessage() and check the message string.
Further you can refer : Retrieving Exceptions

You can process your Exception, check the condition if you want to handle or not. If not handled, you can throw the original Exception to outer catch blocks to process.
try {
... your code here ...
} catch (SqlException e) {
if (e.getErrorCode() == ...) {
... do your exception handling
} else {
throw e; // <-- re-throw the original Exception
}
}

You cannot do this. Exceptions are caught in Java based on their type (SQLException in this case). But still, you can catch all SQLException objects, inspect the exception message, and thhen process only those exceptions you are interested in (those with the specified message).

Related

Java If NoSuchElementException is returned

How can I make an if statement to check if "NoSuchElementException" is returned from a function? Something similar to what I have below.
if (functionReturns == "NoSuchElementException")
How can I make an if statement to check if NoSuchElementException" is
returned from a function?
If you meant that your function returns a String with the value as NoSuchElementException, use equals instead of == :
if("NoSuchElementException".equals(functionReturns)) { }
If you meant that your function can throw a NoSuchElementException, use a try-catch. The catch block will be triggered when the function throws a NoSuchElementException.
try {
function();
} catch(NoSuchElementException e) {
//NoSuchElementException was thrown
}
If you meant that your function actually returns an instance of NoSuchElementException, you can use :
NoSuchElementException.class.isAssignableFrom(functionReturns)
If method is throwing exception then simple use try and catch .
like
boolean isException = false;
try{
//method that throws
}catch(NoSuchElementException e){
isException = true;
//or perform what you like
}
First of all NoSuchElementException or any other Exception is basically Thrown by a method not Returned. So you can/should not check it via return type.
The best approach to handle any type of Exception is try catch blocks. Ex:-
try {
// Probable Exception Throwing code
} catch(NoSuchElementException e) {
// handle/log specific type of error
}
catch(Exception e) {
// handle/log Generic error if none specific is defined
}
Find more about Exception in the Official Docs here
if you are using if statement then there must be thrown more than one error so in java 7
In Java 7 it was made possible to catch multiple different exceptions in the same catch block. This is also known as multi catch.
Before Java 7 you would write something like this:
try {
// execute code that may throw 1 of the 3 exceptions below.
} catch(NoSuchElementException e) {//work as if if (functionReturns == "NoSuchElementException")
logger.log(e);
} catch(NoSuchElementException1 e) {//work as if if (functionReturns == "NoSuchElementException1")
logger.log(e);
} catch(NoSuchElementException2 e) {//work as if if (functionReturns == "NoSuchElementException2")
logger.severe(e);
}
As you can see, the two exceptions NoSuchElementException1 and NoSuchElementException2 are handled in the same way, but you still have to write two individual catch blocks for them.
In Java 7 you can catch multiple exceptions using the multi catch syntax:
try {
// execute code that may throw 1 of the 3 exceptions below.
//combind way to catch multiple error
} catch(NoSuchElementException1 | NoSuchElementException2 e) {
logger.log(e);
} catch(Exception e) {
logger.severe(e);
}
Notice how the two exception class names in the first catch block are separated by the pipe character |. The pipe character between exception class names is how you declare multiple exceptions to be caught by the same catch clause.
This way worked for me.
if(function.equals("NoSuchElementException"))

Will an assertion error be caught by in a catch block for java exception?

Code:-
try {
Assert.assertEquals("1", "2");
} catch (Exception e) {
System.out.println("I am in error block");
}
If the assert statements fails, I would like to capture the error in the catch block. I am trying with the above code and its not happening.
Will the assertion error be caught by in a catch block for java exception?
You have almost answered your own question. Your catch block will not catch the AssertionError that the Assert throws if it fails, because it is an Error (or, more specifically, it extends java.lang.Error). See the docs for more information on this. Your catch block only catches Throwable objects that extend java.lang.Exception
If you really want to catch it - you need to use
catch (AssertionError e) {
...
However, as others have mentioned, this is a very unusual way to use assertions - they should usually pass and if they fail it is very unusual for you to want to carry on the program execution. That's why the failure throws an Error rather than an Exception. You can read more about (not) catching Error in this question.
If you just want a test the variable value, it is preferred to use if ( variableName == "1")
NB if you are testing unit-test helper code, like a matcher, it might make sense to catch the AssertionError.
If you want to catch both Exception and Error instances use:
...
catch (Throwable t)
{
...
}
Since both Exception and Error extend Throwable.
Well, I believe you are using JUnit for writing your tests. In that case, you should not catch your Assert.assertEquals() because they should pass for normal test execution. If it throws any exception, it means that your code is not performing as it should.
If you want to catch the errors in that way you need something like the following:
if (num == 1 || num == 2) {
throw new Exception();
}
You could create your own exception class and pass in the message you want.

Why there is no option to re throw the exception with custom message?

To customize the error message, we need to do the following
Catch the exception
wrap the exception to another Exception
Re throw the exception
Instead why there is no way to just change the Exception error message and re throw it?
I know it is a basic question, but curious to know your opinions.
Take an example:
try
{
// Any operation which might throw NumberFormatException.
int result = 1 / 0;
} catch (NumberFormatException e)
{
// Observe that if I just throw by 'e' then I will get message as '/ by zero'
throw e;
// OR I wrap the exception (optional) and throw new exception with custom message.
throw new NumberFormatException("<Custom Message> instead of '/ by zero'");
// Instead, wouldn't it be easy if I could just overwrite the exception message of NumberFormatException?
// below code isn't valid, but wondering why Java doesn't let me do this?
e.setMessage("<Custom Message> instead of '/ by zero'");
throw e;
}
catch (NumberFormatException e){
e.setMessage("<Custom Message> instead of '/ by zero'");
throw e;
}
This is a bad way of handling exception if Java let you to do so. Now you loss the original message and loss the stack trace of the exception. That's why no point of let you to set the message,and no point to catch and throw same exception, Just throw it and handle it in upper level.
If you want to do something you are trying to do, you can do it in following way
catch(NumberFormatException e){
throw new MyException("your message matched with the method" ,e);
}
In this case you can see, both original message and stackTrace is preserve while you are adding your message.
It is possible to write some real buggy code if you could change the message of the exception. An Exception is part of the contract of a method. It reflects what happened at some point deep in the code.
It is there to communicate about something that went wrong deeper in the code. It is not your business to change this message. Either you throw the message up to some other method that can deal/understand how to go about this Exception, or you catch the exception and throw your own Exception if you so wish.
Basically the message is an intrinsic part of the Exception (immutable if you wish).
And it is also not too hard to write something like
catch(Exception e){
throw new Exception("custom message" ,e);
}
Which is one line shorter than :
catch(Exception e){
e.setMessage('my custom message');
throw e;
}
Ask yourself, if your job was a messanger on a horse who has to send a letter from person A to person B, and you read the letter and realised that some additional information needed to be updated. Would you rewrite the letter and put it back in the envelope, or would you write a post-it note and stick it on the envelope?
There's no setMessage() meghod, you could throw a different instances of NFE but with the original exception as its cause:
catch (NumberFormatException e) {
throw new NumberFormatException("<Custom Message> instead of '/ by zero'", e);
}
It's important to preserve the context of the exception so the stacktrace is as useful as possible to the caller.

log all occurrences of an exception type app-wide

I have an application, and in it there are about 100 different classes that throw type FooException. Sometimes these exceptions get caught and handled, sometimes they are uncaught and bubble up to get logged.
However, I want to be able to send all occurrences of FooException to a special log file regardless of how the exception eventually gets handled. What would be a way to implement this? Could I somehow do it with an event listener pattern?
You can catch all the exceptions of type FooException, special-log them and re-throw them.
try {
// throws exception
} catch (AnotherException e) {
//handle this one
} catch (FooException e) {
specialLog(e);
throw e;
} catch (YetAnotherException e) {
// handle
}
You only do this for the occurrences you want to bubble up.
For the ones you already handle, just do the same thing but don't re-throw.

Exception Handling

catch (Exception ex)
{
DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
msg = "Unable to save data";
status = false;
}
This piece of code would throw an status as false, if i encounter an error.
Instead should i thrown New exception.
Is this the right way.
How can i handle exception in a better way.
Prefer throwing exceptions to returning error codes/status.
Returning an error code means the caller should always remember to check for it. Throwing the exception allows the calling code to make the decision of what to do (an normally the higher up the decision, the better it can be made).
First, don't catch Exception. Catch a specific subclass.
Second, yes it may be that an underlying IOException, which is what this looks like, should be wrapped in an app-specific exception. You could have, for instance:
final class DBGlobalsException extends Exception
{
Field somethingDBGlobalsSpecific;
//where this is shorthand for chained constructors that look like Exception
DBGlobalsException(String message, Throwable cause)
{
super(message,cause);
}
// elaborate your exception with whatever error state you want to propagate outwards
void setField(Field ...) {}
}
And you could then
catch (IOException ex) {
DBGlobals.Error("OHMjson.Graph.saveLastGraphName - Error: " + ex.getMessage());
msg = "Unable to save data";
status = false;
DBGlobalsException dbe = new DBGlobalsException(msg,ex);
dbe.setField(status /* or whatever */);
throw dbe;
}
See also: Throwing Exception, Throwing new and old exceptions, Rolling your own. That's just a few, there are a bunch of great SO Q+A's on exception handling, chaining, etc. Some useful best-practices stuff outlined at WikiBooks.
Also read Oded's answer and think it through... your exception should encapsulate whatever status (error codes, flags, etc...) are required for the outer code to recover from the condition -- or it should be an unrecoverable condition (see RuntimeException).
Finally, the canonical Effective Java reference: Item 43: Throw Exceptions Appropriate to the Abstraction.

Categories

Resources