Is it possible, that below condition in "My code" will be fulfilled(true)? I belive that no, beacuse getRootCause returns object casted to Throwable. So it should check, if Throwable is a subtype of MyOwnException, which is not true. So, in general, it is wrong way to use getRootCause to handle exceptions, is not it?
MyOwnException part
public class MyOwnException extends Exception {
// ....
}
Apache's ExceptionUtils.getRootCause
public static Throwable getRootCause(Throwable throwable) {
List list = getThrowableList(throwable);
return (list.size() < 2 ? null : (Throwable)list.get(list.size() - 1));
}
My code
try {
// do something
} catch (Exception e) {
try {
Throwable exc = ExceptionUtils.getRootCause(e);
if (exc instanceof MyOwnException) {
// do something
}
}
}
instanceof will check against the actual run-time type of an object instance. It does not matter what the declared compile-time type of the variable that holds the object is.
So your condition works: If the root cause is a MyOwnException then your if block's body will execute.
Related
Consider the following code:
auditlog.getMessages()
.stream()
.filter(m -> messageId.equals(m.getMessageid()))
.findFirst()
.orElseThrow(NoMessageFoundException::new)
NoMessageFoundException is a custom unchecked exception, extending from RuntimeException. When findFirst() returns an empty optional I expect a NoMessageFoundException to be thrown, however, the code just carries on.
Is it impossible to do this with unchecked exceptions?
I could change NoMessageFoundException to a checked exception, but then I would have to write a try/catch block or some sort of wrapper to catch the exception as explained here but I wish to not do that.
Any ideas?
There is no limitation on the type of Exception that can be thrown.
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
if (value != null) {
return value;
} else {
throw exceptionSupplier.get();
}
}
If the code "carries on", it means that a message is found.
if the exception is not getting throw is because there is at least one element remaining after the filter action...
see this example:
public class ASFasf {
public static void main(String[] args) {
List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);
Integer iR = l.stream().filter(x -> x > 100).findFirst().orElseThrow(NoMessageFoundException::new);
System.out.println(iR);
}
}
class NoMessageFoundException extends RuntimeException {
public NoMessageFoundException() {
super("Opala!!");
}
}
iR will never get printed, and a NoMessageFoundException is thrown....
I'm relatively new to Java and I have run into an issue which I'm unable to figure a way to get around.
Here is my code:
// Ex2 is a child of Ex1
public T method(someType someArg) throws Ex1{
try{
someFunc() // Throws both Ex1 and Ex2
T ret = someOtherFunc() //Throws Ex1, cannot declare/initialize ret outside
return ret
} catch(Ex2){
//do something
} catch(Ex1){
//do something
}
}
Now java complains about missing return type whereas it DOES NOT complain when I remove Ex2 handling/catching.
Your method must return a T, you could add return null; as the last statement. Or, modify the visibility (and default value of) ret like
public T method(someType someArg) throws Ex1{
T ret = null;
try{
someFunc(); // Throws both Ex1 and Ex2
ret = someOtherFunc();
} catch(Ex2){
//do something
} catch(Ex1){
//do something
}
return ret;
}
If you are merely catching the exceptions and not throwing any exceptions after handling/logging them, then the method is handling the errors correctly but not returning anything (boom, compilation error).
If you are going to handle the exceptions yourself, you need to either return a null (or other reasonable invalid value) or re-throw the caught exception.
If you are going to rethrow an exception (other than ex1), make sure you add it to the method signature
For example:
// Ex2 is a child of Ex1
public T method(someType someArg) throws Ex1{
try{
someFunc() // Throws both Ex1 and Ex2
T ret = someOtherFunc() //Throws Ex1, cannot declare/initialize ret outside
return ret;
} catch(Ex2 ex2){
// either re-throw the exception (or return null instead)
throw ex2;
} catch(Ex1 ex1){
// or return a null value (you can re-throw the exception instead)
return null;
}
// you can also return null here if you want to catch/handle both exceptions separately but want to return null in either case
// return null;
}
How would one go about overloading the getCause() method in a throwable object ?
I have the following but it doesn't seem to work as it says that it cannot be overloaded with a string.
public class MyException extends RuntimeException {
String cause;
MyException(String s) {
cause = s;
}
#Overwrite public String getCause() {
return cause;
}
It is illegal to have two methods that only differ in their return type. Suppose someone wrote:
Object obj = myException.getCause();
That is perfectly legal java, and the compiler has no way to figure out if it's the String version or the Throwable version.
Likewise you can't replace the superclass signature since this is also perfectly legal:
Throwable t = new MyException();
Throwable t0 = t.getCause();
//Returns String?!?!?!?
Accepted answer clears the point :
It is illegal to have two methods that only differ in their return
type
But if you have a situation where, getCause() should return the custom cause in MyException, in case original cause is null.
In that case, you can use initCause() to set the cause and override toString() method. So, when getCause() method will be called on object of MyException, it will show the message from customCause instead of null.
What is the use: In legacy system, if you have used getCause() on MyException object while logging, and now you want to add the custom cause to it without changing lot of code, here is the way.
public class MyException extends RuntimeException {
String customCause;
MyException(String s) {
super(s);
customCause = s;
}
#Override
public synchronized Throwable getCause() {
if (super.getCause() != null) {
return this;
} else {
this.initCause(new Throwable(customCause));
return this;
}
}
#Override
public String toString() {
String s = getClass().getName();
String message = getLocalizedMessage();
if (message == null) {
message = customCause;
}
return (message != null) ? (s + ": " + message) : s;
}
}
References:
https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#initCause(java.lang.Throwable)
https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html
This question already has answers here:
Check chains of "get" calls for null
(11 answers)
Closed 3 years ago.
I intend to make a common dynamic null check function on any object before doing some work on it.
For example:
Class A{
B b;
// with getters and setters of b
}
class B{
C c;
//with getters and setters of c
}
class C{
BigInteger d;
//with getters and setters of d
}
now, I want to check whether objA.getB().getC().getD() returns some value or throws NullPointerException?
By common I mean I can pass any kind of object to it, something like below function
CheckNull.checkingDynamicNull( "objA.getB().getC().getD()" )
will return me true or false depending on the case.
Any ideas?
Unfortunately it is not possible to pass a funktion into a method in Java (yet, Java 8 will). Also, if you pass the variable name as String this wont work, since the recieving method has no way of knowing what Object is mapped to that variable (if you ignore reflection but even with that you are screwed if its a local variable).
Another way would be to do something like this
boolean nullCheck(Object obj, String Methods)
and then parse the String to Methods and invoke them on the object. But that wont work if you have Methods with arguments.
In short: It's more trouble then it's worth
In the most cases you want to have something like this
if(object == null){
//error behavior
}
This assumes that you want to throw a certain Exception, have means to get a value for the null object elswhere or want to do something before you throw an exception.
If you simply want to throw an Exception (that is not a NullPointerException)
assert object != null
What about this:
public boolean checkingDynamicNull(A objA) {
try {
objA.getB().getC().getD().toString();
} catch(NullPointerException npe) {
return true;
}
return false;
}
To know if a statement would return null, you would have to execute it first. Even if you somehow manage to execute the statement given in String to your method, it would be no different than just running it and checking whether the result is null, or catching the NullPointerException.
You are looking for something that will be part of Java 8 (or 9 or 10?) soon. Cf. http://viralpatel.net/blogs/null-safe-type-java-7-nullpointerexception/
With reflection it could be something like that:
nullCheck(objA, "getB", "getC", "getD" );
public static boolean nullCheck(Object obj, String... methods) {
Object o = obj;
Class<?> clazz = obj.getClass();
Method method = null;
try {
for( String name : methods ) {
method = clazz.getMethod( name, null );
o = method.invoke( o, null );
clazz = method.getReturnType();
}
} catch( NullPointerException e ) {
System.err.println(clazz.getSimpleName()+"(null)."+method.getName());
return false;
} catch( NoSuchMethodException e ) {
e.printStackTrace();
} catch( SecurityException e ) {
e.printStackTrace();
} catch( IllegalAccessException e ) {
e.printStackTrace();
} catch( IllegalArgumentException e ) {
e.printStackTrace();
} catch( InvocationTargetException e ) {
e.printStackTrace();
}
return true;
}
System.out.println(nullCheck(GraphicsEnvironment.getLocalGraphicsEnvironment(), "getDefaultScreenDevice", "getDisplayMode", "toString"));
System.out.println(nullCheck(GraphicsEnvironment.getLocalGraphicsEnvironment(), "getDefaultScreenDevice", "getFullScreenWindow", "doLayout"));
brings
true
false
'Window(null).doLayout'
you can achieve this by using reflection, here is your method:
public boolean dynamicNullCheck(Object o, String path) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Object object= o;
for (String element : path.split("\\."))
{
Field field = object.getClass().getDeclaredField(element);
field.setAccessible(true);
Object fieldVal = field.get(object);
if (fieldVal!=null)
{
field.setAccessible(true);
object = fieldVal;
}
else
{
return true;
}
}
return false;
}
use it by giving your root element and path to each object, ie dynamicNullCheck(objA,"b.c.d")
I have an application which uses code that produces various types of objects and data structures, returning them as Object instances, and would like a generic way of establishing whether any of those objects is "empty" (or null).
(This is not a matter of design, or of whether such a method should be used, but a question of optimizing the solution to an existing requirement.)
So, here is a simple go:
public static boolean isEmpty(Object content)
{
if (content == null)
{
return true;
}
else if (content instanceof CharSequence)
{
return (((CharSequence)content).length() == 0);
}
else if (content instanceof Collection<?>)
{
return ((Collection<?>)content).isEmpty();
}
else if (content instanceof Object[])
{
return (((Object[])content).length == 0);
}
else // Use reflection (an exaggeration, for demo purposes)
{
try
{
Method isEmpty = content.getClass().
getDeclaredMethod("isEmpty", (Class<?>[])null);
if (isEmpty != null)
{
Object result = isEmpty.invoke(content, (Object[])null);
if (result instanceof Boolean)
{
return (Boolean)result;
}
}
}
catch (Exception e)
{
}
}
return false;
}
Any ideas for potential improvements, in terms of either performance, or coverage?
For instance, reflection could be also used to establish whether the object has a length() or size() method, invoke it and see if the result is 0. (In reality, reflection is probably too much, but I am including it here for completeness.)
Is there a top-level class very commonly used, which has a length() or size() method, instead of the isEmpty() method, to include in the above case, similarly to Collection that has isEmpty()?
Instead of the ugly instanceofs, split up the method into several methods with the same name but different args. e.g.
static boolean isEmpty(Object[] array)
static boolean isEmpty(Collection collection)
static boolean isEmpty(CharSequence cs)
Instead of reflection, if you really want your own interface for special objects, declare that interface, and then, for consistency with the above, offer the static utility
static boolean isEmpty(IMayBeEmpty imbe);
This method would at least solve your problem of the generic isEmpty(Object) problem. However, you don't get compile time safety with this, and calling it without the method existing for the exact type requested will yield a runtime error. Note the "MethodUtils" class is from apache commons-beanutils, though you could easily use reflection directly, but for the sake of simplicity, i'm using beanutils here.
The "invokeExactcMethod" method looks for a static method in the given class with the given name that has the compatible parameters of the object array being passed. So if the runtime type of the object is ArrayList, it would look for isEmpty(ArrayList) then isEmpty(AbstractList) then isEmpty(List). It then invokes that method if it can find it, otherwise it throws a NoSuchMethodException.
public class MyUtility {
static boolean isEmpty(Object object) {
if (object == null) {
return true;
}
else {
try {
return MethodUtils.invokeStaticMethod(
MyUtility.class, "isEmpty", new Object[]{object});
}
catch (NoSuchMethodException e) {
throw new IllegalArgumentException(e);
}
catch (IllegalAccessException e) {
throw new IllegalArgumentException(e);
}
catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
}
the "invokeExactStaticMethod" is more deterministic and doesn't use assignment compatibility, but exact signature matching. That means isEmpty(List) would never match anything because you can't construct anything of that type.