code not throwing exception - java

I am trying to execute below written code and the code should throw an exception but it isn't doint it
try {
Field.class.getMethod("getInt", Object.class).setAccessible(false);
StringSearch.class.getMethod("searchChars",cc.getClass(),pattern3.getClass()).setAccessible(false);
ss4.getClass().getMethod("searchChars",cc.getClass(),pattern3.getClass()).setAccessible(false);
ss4.searchChars(cc,pattern3);
ss4.searchString(str,pattern);
}
catch(NoSuchMethodException ex){
ex.printStackTrace();
}
it should actually throw IllegalAccessException.
ss4 is an object of class BNDMWildcardsCI (one of the algo for String search)
cc, pattern3 are character arrays
str, pattern are Strings
why it isn't throwing an exception, it is not throwing the NoSuchMethodFound exception means that it is able to find the method also i tried to print the isAccessible and it says false
but when i run the tests it doesn't throw any exception

To the best of my knowledge, if a method is declared public (or otherwise accessible), setAccessible(false) can't make it private. It's only useful if you have a private method and you previously called setAccessible(true).

The method setAccessible(boolean) work on object reflect not on normal object. In your code you set it on a method object not on the ss4 object.
To show my point:
Class<?> clazz = ss4.getClass();
Method searchCharsMethod = clazz.getMethod("searchChars",cc.getClass(),pattern3.getClass());
searchCharsMethod.setAccessible(true);
You have set the accessible flag to false on object assigned to searchCharsMethod not ss4.
As bonus see what happen when you call
searchCharsMethod.invoke(ss4,cc,pattern3);
For more please read the documentation

Related

Optional IncorrectResultSizeDataAccessException

public Optional<Student> findStudent(String name, String` surname,String nickname)
{
try {
return repository.findOne(predicates.hasSpecifications(name, String surname,nickname));
} catch (IncorrectResultSizeDataAccessException e) {
return Optional.empty();
}
}
the method findOne() throws IncorrectResultSizeDataAccessException if more than one entry is found for the predicate inside of it. Is this the best way to handle the exception thrown? or should the caller handle the exception using something like: optional.orElseThrow()... but this method only handles NoSuchElementException (if no value is present) and not IncorrectResultSizeDataAccessException (If more than 1 RESULT)...
Any ideas guys?
Yeah, this would be the best way to do it.
I'm assuming hasSpecifications is a custom method which returns the id you wish to use to index the database
The thing is "findOne" and "hasSpecifications" are two methods independent of each other.
When we talk about abstraction, in methods then the only things that matter are their input parameters, the return values and the errors that may or may not be thrown.
This means "findOne" only cares about what "hasSpecifications" evaluates to. If there is an error or exception thrown while "hasSpecifications" is still executing then this error abruptly terminates the program (unless caught) and findOne wont even be evaluated (Because it was waiting for the id). A NoSuchElementException cannot be thrown because findOne hadn't started executing yet.
So since it's a custom method, the error handling has to be done by you, as you just did.
To make it more obvious extract predicates.hasSpecifications into a variable on a preceeding line and then place the variable in "findOne"

What is the best runtime exception to use when mandatory input is missing

I have service, a simple class that need to take input and run some business logic. Before executing this service, the user must set all the data. In general, it look like this:
public class TestService extends InnerServiceBase {
/**
* Mandatory input
*/
private Object inputObj;
#Override
protected ErrorCode executeImpl() {
//Some business logic on inputObj
return null;
}
public void setInputObj(Object inputObj) {
this.inputObj = inputObj;
}
}
What is the best runtime exception to throw in case the inputObj is null ?
IllegalStateException seems like the best fit. The object is not in the correct state to have executeImpl() called on it. Whatever exception you use, make sure the error message is helpful.
Whether you should be using an unchecked exception at all is a whole other question...
Depends on the scenario.
If this is part of an API that another developer is using, throwing NullPointerException is reasonable since you don't want that input to be null. Adding a descriptive exception message would be helpful.
If you're not interested in throwing an NPE, or this is part of code that's not going into an API, then you could throw an IllegalArgumentException, as null could be considered an illegal argument.
If setInputObj is called with a null argument, and that's not valid, then throw NullPointerException. There's some debate over the "correct" exception here (IllegalArgumentException or NullPointerException for a null parameter?), but Guava, Apache Commons Lang and even the JDK itself (Objects.requireNonNull) have settled on NPE.
If executeImpl is called before inputObj has been set, throw IllegalStateException.

Throwing and catching exceptions correctly

So I have this one question. Lets say we have classes: Main, Info, Cats, Food
Now, lets say that in main we create new object Info. In Info object we are saving list of Cats that have been created. Cats are being created and stored in Info class and Food is being created and stored in Cats class. Now lets say, that in Main class, I want to get specific Food object, which is stored in Cats class. So, in order to do so we do the following:
Info.getFood(name). Then in Info's getFood method we say Cats.getFood(name). Finally, in Cats class we have method getFood, in which we try to find Food object by its field "name". If we are unable to find such an element, we throw NoSuchElement exception rather than return an object. Here is my question:
If we throw exception in Cats class getFood method, should we catch that exception in Main class (where our interface is), in Info class (which is our system class) or in both of them?
Generally speaking, inside a method, if you can do something with the Exception being thrown (log an error, show an error message, make a different decision in your code, etc), then you should catch it. Otherwise, just throw it to the calling method.
As with many other coding practices, it all boils down to what you and your team agree on.
A concrete example which isn't related to your code, but which will show you how the decision process can be made. Assume the following code:
public MyConfiguration loadConfiguration () throws ConfigurationException {
MyConfiguration config = null;
try {
readConfigurationFromFile ();
// Parse configuration string
} catch (IOException ioex) {
throw new ConfigurationException (ioex);
}
return config;
}
private String readConfigurationFromFile () throws IOException {
String configuration = "";
// Read a file on disk, append data to the string.
return configuration;
}
In readConfigurationFromFile (), if an exception occurs while reading the file, you'll get an IOException. At this point in the code, there's no real action you can take, since this method only reads the configuration file, appends the data to a String, then returns it.
In loadConfiguration (), you can surround the call to readConfigurationFromFile () with a try/catch, and throw a more generic exception (ConfigurationException). Again, at this point, there's nothing you can do with the exception, except wrap it in a new exception which adds more context information to the original exception that was thrown.
Now assume that there's two flavors of your software: a GUI version, and a command-line version. If you are running the GUI flavor, then the method calling loadConfiguration could decide to show an error message to the user whenever a ConfigurationException is being thrown, so that the user knows that something happened. If you are running the command-line version, then maybe it would be more logical to add an entry to some error log with the exception that was caught.
The following site says "Most of the developers are embarrassed when they have to choose between the two options. This type of decision should not be taken at development time. If you are a development team, it should be discussed between all the developers in order to have a common exception handling policy."
http://en.wikibooks.org/wiki/Java_Programming/Throwing_and_Catching_Exceptions
It depends a lot on what you want to do after throwing that exception.
Say for instance that if all you want is to return any food object from any cat (and as you said 'Info' stores lots of cats) then you might have a catch in Info where you catch the NoSuchElement exception and then create some logic that moves onto the next Cat in Info to get its food! Finally if you exhaust all the 'Cats' in Info with no food found, you can throw another exception inside Info that you catch in Main that lets main know, "There's no food".
Again that's just an example. As people have said, it's not a "Always do this..." kind of answer. It depends greatly on what you need to do when handling that exception

Obtaining the original Java class while using instanceof and casting

First off, for anyone out there who abhors, detests and despises the instanceof operator, I understand your concerns with it, but am stuck using it. That's because I don't have the authority to completely refactor the way another development team set a project up, so unless I'm missing somethin here, I just don't see any way of avoiding it.
I have a Java POJO that cannot be changed, and allows you to set an Exception as one of its properties:
public class Message {
private Exception exception;
public void setException(Exception exc) {
this.exception = exc;
}
}
Again, I can't change this Message class.
I am writing an error handler method that gets passed a MessageContainer instances, and I need logic to do different things depending on what type of exception was set on the container's Message:
public class ErrorHandler {
public void handle(MessageContainer container) {
Message msg = container.getMessage();
Exception exc = msg.getException();
if(exc instanceof FizzException)
System.out.println("Do x");
else if(exc instanceof BuzzException)
System.out.println("Do y");
else
System.out.println("Do z");
}
}
Again, I can't change the fact that ErrorHandler#handle is passed a MessageContainer and not an injectable Message instance.
So, even though I really don't like to use instanceof, I don't see any other way of accomplishing this logic (but by all means, please make suggestions...as long as they don't involve making changes to Message, MessageContainer, or the handle(MessageContainer) method!).
But even with using instanceof, how does this code even work? Once you pull the Exception out of the Message, I don't think any of the instanceofs will fire, because its cast to an Exception, with no way to detect if it's BuzzException, FizzException, etc. What are my options here? Thanks in advance.
This code will work as expected. During runtime, instanceof statements will compare the actual type of exc, and not just assume this is only an Exception. If the only statement that worked was exc instanceof Exception, instanceof would be totally worthless :)
Another solution (which I would avoid to use) would be to compare fully qualified class names:
String fqcn = exc.getClass().getName();
if (fqcn.equals("com.foo.FizzException") {
// etc.
}
The cast to exception on
Exception exc = msg.getException();
does not erase the exception runtime type. It has merely cast it to a base type. The instanceof will still work. However, if your FizzException extends BuzzException, then you will need to do the instanceof checks in the other order. i.e. check for the most derived type first.
Otherwise, it will go into the base class check clause instead of the derived one.
It's not clear what you want. If the exceptions are all "given" and you can't change their implementations then you can use exception.getClass().getName() to get the class name and, maybe, look it up in a table or whatever to pick your course of action.
If you can change many of the exception implementations have them all implement an interface that provides a "functionality()" method or whatever. If an given Exception object is instanceof MyFunctionalityInterface then cast to MyFunctionalityInterface and call functionality() to have it return the info you need to guide your actions. Then use instanceof or getClass().getName() to manage the Exception classes you can't change.

Does throwing exception in JS property assignment in Rhino makes sense?

I came across a design that overrides [Scriptable.put][1] in a subclass of ScriptableObject to do some conversion. If the conversion fails the code is throwing an exception. Which means that property assignments like following code can cause a runtime exception to be thrown
aScriptable.dateOfArrival = aVar;
By default rhino wouldn't let the script catch a runtime exception thrown during [Scriptable.put][1]. So catch block in following code will never run:
try{
aScriptable.dateOfArrival = aVar;
}catch(e){
//will not run even if above assignment generates an exception. Script will be terminated instead
}
Overriding ContextFactory.hasFeature() with following code makes the above catch block work:
protected boolean hasFeature(Context cx, int featureIndex) {
if(featureIndex == Context.FEATURE_ENHANCED_JAVA_ACCESS){
return true;
}
return super.hasFeature(cx, featureIndex);
}
My question is that whether the design decision to make property assignment throw exception is correct or property assignments are never supposed to throw exceptions?
[1]: http://www.mozilla.org/rhino/apidocs/org/mozilla/javascript/Scriptable.html#put(java.lang.String, org.mozilla.javascript.Scriptable, java.lang.Object)
IMO it doesn't make sense to throw an exception by design from the put method that JS code can't catch. I think throwing an exception on setting a property is fine, although not that common. Note that JS code can easily reconfigure a property (in ECMAScript 5) with a custom setter that throws.
On the other hand, I think it would be quite surprising if a property getter throws an exception.

Categories