May be it could be silly,but I want to clear my the technical understanding of this code:
import netscape.*;//ldap jar
public class A {
public void method() {
...
try {
//code is written here.
LDAPSearchResults lsr = ldi.search(LDAPConnectionInfo.MY_SEARCHBASE,LDAPConnectionInfo.MY_SCOPE,LDAPConnectionInfo.MY_FILTER,null,false);
while(lsr.hasMoreElements()){
LDAPEntry findEntry = (LDAPEntry)lsr.nextElement();
} catch(...) {
}
}
}
Now I call another class
public class B {
A a = new A();
//here I want to use attributeName
}
How could I access A class's member(in try block) in B class.
Any way to handle try block code for reuse in another class.
How could I handle all those exception in another class.
Any modification should I need...
Calling method of Object type.
public class C{
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public Object method(){
attributeName=lAttribute.getName();
}
}
How could print this Object type method into String(in a jsp page)... any inputs
You'll need a member in class A and a getter:
public class A {
private String attributeName;
public String getAttributeName() {
return attributeName;
}
public void method(){
...
try {
//code is written here.
attributeName = lAttribute.getName();
}
catch() {
}
}
}
Then:
public class B {
A a = new A();
// somewhere
String str = a.getAttributeName();
}
There's no way to access a method's private variables like you did in the original example, as they only exist on the stack during the method call.
Edit: I noticed another question:
How could I handle all those exception in another class.
I assume you want to call your method somewhere else and catch the exceptions there. In that case you can use the throws keyword to communicate that your method will pass exceptions to the caller:
public class A {
public void method() throws IOException {
//code is written here.
String attributeName = lAttribute.getName();
}
public void anotherMethod() {
try {
method();
} catch(IOException ex) {
...
}
}
}
then if some other piece of code calls method it will be forced to either handle or further propagate the exception.
How could I handle all those exception in another class.
In your calling class you can catch Throwable (which will catch all exceptions and errors)
try {
....
}
catch (Throwable t) {
//do something with the throwable.
}
if you do not want to catch Errors (Ive only done this when messing around with ImageIO and had memory problems) in Java then catch Exception instead
Any way to handle try block code for reuse in another class
here you could create a method in another class and then call it within your try /catch block
public class XYX {
public void methodForTry() throws Exception {
//do something
}
}
try {
new XYZ().methodForTry();
}
catch (Exception e){
}
You may or may not want to create new XYZ here. It depends what state this object may or may not hold.
As to the last questions I think Tudor's answer covers this
Your question may be about extracting the code template
try { ... do stuff ... }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
Where you only want to change the ... do stuff ... part. In that case you'd need closures, which are coming with Java 8, and today you'd need something quite cumbersome, of this sort:
public static void tryCatch(RunnableExc r) {
try { r.run(); }
catch (MyFirstException e) { ...handle ... }
catch (MySecondException e) { ...handle ... }
... more catch ...
}
where RunnableExc would be an
interface RunnableExc { void run() throws Exception; }
and you'd use it this way:
tryCatch(new RunnableExc() { public void run() throws Exception {
... do stuff ...
}});
why not return it?
public String method() {
String attributeName
try {
//code is written here.
attributeName = lAttribute.getName();
} catch(...) {
}
return attributeName;
}
public class B {
A a = new A();
String attributeName = a.method();
}
Related
I have a class that has many methods. All the methods throw one exception when data is not ready. In that case, I want to retry the method after a certain interval. So in catch, I need to add retry logic. The same logic i need to add for all methods.
Is there some way/pattern to execute same logic for all catch clause without copy paste
One way I could think of is to write my own Exception class and Throw that exception. And do this retry logic from My Exception class.
Is there any other better way to this?
class MyClass {
public void method1() {
try {
//do some logic
} catch (Exception e) {
//retry logic
//existing exception handling logic
}
}
public void method2() {
try {
//do some logic
} catch (Exception e) {
//retry logic
//existing exception handling logic
}
}
public void method3() {
try {
//do some logic
} catch (Exception e) {
//retry logic
//existing exception handling logic
}
}
}
EDIT:
class MyClass {
public void method1(int a, int b) {
try {
//do some logic
} catch (Exception e) {
Object args[] = {a,b};
executeLater("method1",args);
//retry logic
//existing exception handling logic
}
}
public void method2() {
try {
//do some logic
} catch (Exception e) {
Object args[] = null;
executeLater("method1",args);
//retry logic
//existing exception handling logic
}
}
public void method3(String abcd, int a) {
try {
//do some logic
} catch (Exception e) {
Object args[] = {abcd,a};
executeLater("method1",args);
//retry logic
//existing exception handling logic
}
}
public boolean executeLater(String methodName, Object args[]){
//Execute given method with the supplied args
return true;
}
}
Added code that shows what i would be doing in each catch clause
boolean processCompleted=false;
while(!processCompleted){
try{
doProcess();
processCompleted=true;
}catch(Exception e){
Thread.sleep(10000);
}
}
This might give you an idea. It keeps try to call doProcess until it doesn't throw exception. If any exception occurs, waits 10 seconds.
Well, you could extract the whole catch block content to a method and call that one, but this only works if your retry logic is not dependent on the specific method. And it also requires a try-catch in every method.
Instead, use functional programming to shorten it:
public class Playground
{
public static void main(String[] args)
{
new Playground().method2(1, 2);
new Playground().method1();
}
public void method1()
{
tryAndTryAgain(() -> {
// logic 1
System.out.println("no params");
throw new RuntimeException();
});
}
public void method2(int a, int b)
{
tryAndTryAgain(() -> {
// logic 2
System.out.println(a + " " + b);
throw new RuntimeException();
});
}
public static void tryAndTryAgain(Runnable tryThis)
{
try
{
tryThis.run();
}
catch (Exception e)
{
new Timer().schedule(new TimerTask()
{
#Override
public void run()
{
tryAndTryAgain(tryThis);
}
}, 1000);
// existing exception handling logic
}
}
}
The exact structure depends on your specfic implementation, but it should give you an idea how to structure it. The benefit is that all those methods can concentrate on the business logic, and the retry logic and exception handling are done in a util method. And that util method doesn't even need to know anything about parameters, methods, or anything, because all the business logic is contained in the Runnable.
For instance:
public Object foo(string something, Boolean flag, Object obj){
try{
if(flag){
//some code
}
} catch(Exception e) {
// handle exception
}
}
public Object doo(string something, Boolean flag){
try{
if(flag){
//different code
}
} catch(Exception e) {
// handle exception
}
}
public Object roo(string something, Boolean flag, Integer id){
try{
if(flag){
//a bit of code
}
} catch(Exception e) {
// handle exception
}
}
My question is, is there any way to not have all the repeating code in every function (e.g. the try-catch blocks and the ifs)? It would really clear up my project and would help me focus on the important code.
I asked this question already about void functions and noticed that the proposed solution (using a runnable) did not work on functions with return types other than null. Is there a different way to implement this?
Link to my previous (and very related) question: How do I surround different blocks of code with the same repeating block of code?
When you need a return value, you can use a Callable instead of a Runnable. I have modified the example Joffrey gave in the other thread:
class CallableExample {
public static void main(String[] args) {
CallableExample ce = new CallableExample();
System.out.println(ce.foo("", true, ""));
System.out.println(ce.doo("", true));
System.out.println(ce.roo("", true, 1));
}
public Object foo(String something, Boolean flag, Object obj) {
return runCallable(something, flag, new Callable() {
#Override
public Object call() throws Exception {
return "foo";
}
});
}
public Object doo(String something, Boolean flag) {
return runCallable(something, flag, new Callable() {
#Override
public Object call() throws Exception {
return "doo";
}
});
}
public Object roo(String something, Boolean flag, Integer id) {
return runCallable(something, flag, new Callable() {
#Override
public Object call() throws Exception {
return "roo";
}
});
}
private Object runCallable(String something, Boolean flag, Callable c) {
Object result = null;
try {
if (flag) {
result = c.call();
}
} catch(Exception e) {
// handle exception
}
return result;
}
}
Look into the Template Method design pattern and the Execute Around idiom. However, if you find yourself often writing code that catches exceptions, that is a design Smell: ask yourself why you are doing that, and if it is really necessary. Often letting exceptions propagate to the calling context is better.
Why use same code in different methods, instead write a single function for same set of code with if-else-if logic with try catch and minimise your code
for instance:
public Object foo(string something, Boolean flag, Object obj) {
try {
//convert the object type to primitive type data like int, String or any
if(flag) {
//your code
}
catch(Exception ex) {
//your code
}
//return the object;
}
convert Object type data to primitive type and use it accordingly
use if else if logic
how to get method return value isFailed along with exception details if method is failed
class sample
{
booelan isFailed=false;
boolean m1()
{
try{
logic of method
}
catch(Exception e)
{
String cause=e.getMessage();
isFailed=true;
}
return isFailed;
}
}
If the calling method needs to know about the Exception, just let it go through.
m1 doesn't have to return a boolean, it either worked or threw an Exception, so the calling method will know whether it is a success or not.
In this example, the calling method (m1Caller) is in the same class for simplicity .
class sample {
boolean isFailed = false;
void m1() throws Exception {
// logic of method
}
void m1Caller() {
try {
m1();
} catch (Exception e) {
// do whatever you want with the Exception's message
System.out.println(e.getMessage());
isFailed = true;
}
}
}
I need to know how to handle the exceptions in a situation like below. Please assist me,
public interface DCommand {
public Object execute(Class_A car);
}
public class Class_B {
public void getMessage() throws Exception {
throw new Exception("Test error");
}
}
public class Class_A {
Class_B cb = null;
public Class_B getClass_b() {
cb = new Class_B();
return cb;
}
public Object testAction(DCommand command) {
Object returnObject = null;
try {
return (Boolean) command.execute(this);
} catch (Exception e) {
System.out.println("ERROR IN CLASS B" + e.getLocalizedMessage());
}
return returnObject;
}
}
====================== simiulating ============================
public class Test {
public static void main(String[] args) {
Class_A c = new Class_A();
boolean a = (Boolean) c.testAction(new DCommand() {
#Override
public Object execute(Class_A car) {
try {
car.getClass_b().getMessage();
return true;
} catch (Exception ex) {
System.out.println("Error in the simulator.");
}
return false;
}
});
}
}
When I run the above code I need to catch the exception thrown by the Class_B in the Class_A where prints the "ERROR IN CLASS A".
Problem is that you are throwing a type of Exception in your Class B's getMessage method. Instead you should define your own exception by extending java.lang.Exception.
public class ClassBException extends Exception {
public ClassBException(String msg) {
super(msg);
}
}
And then use ClassBException to be thrown in Class B's getMessage method like this
public class Class_B {
public void getMessage() throws ClassBException {
throw new Exception("Test error");
}
}
Now you need to a have separate catch block for ClassBException at any place you are calling Class B's getMessage method.
Add this Methode to class A:
public void runGetMessage()
{
try{
cb.getMessage();
}catch(Exception e){
System.out.println("Error in CLASS A.");
}
}
And change the Execute methode to:
public Object execute(Class_A car) {
try {
car.getClass_b();
car.runGetMessage();
return true;
} catch (Exception ex) {
System.out.println("Error in the simulator.");
}
return false;
}
How would one go about checking to see if a method exists for a class in Java? Would a try {...} catch {...} statement be good practice?
I assume that you want to check the method doSomething(String, Object).
You might try this:
boolean methodExists = false;
try {
obj.doSomething("", null);
methodExists = true;
} catch (NoSuchMethodError e) {
// ignore
}
This will not work, since the method will be resolved at compile-time.
You really need to use reflection for it. And if you have access to the source code of the method you want to call, it's even better to create an interface with the method you want to call.
[Update] The additional information is: There is an interface that may exist in two versions, an old one (without the wanted method) and a new one (with the wanted method). Based on that, I suggest the following:
package so7058621;
import java.lang.reflect.Method;
public class NetherHelper {
private static final Method getAllowedNether;
static {
Method m = null;
try {
m = World.class.getMethod("getAllowedNether");
} catch (Exception e) {
// doesn't matter
}
getAllowedNether = m;
}
/* Call this method instead from your code. */
public static boolean getAllowedNether(World world) {
if (getAllowedNether != null) {
try {
return ((Boolean) getAllowedNether.invoke(world)).booleanValue();
} catch (Exception e) {
// doesn't matter
}
}
return false;
}
interface World {
//boolean getAllowedNether();
}
public static void main(String[] args) {
System.out.println(getAllowedNether(new World() {
public boolean getAllowedNether() {
return true;
}
}));
}
}
This code tests whether the method getAllowedNether exists in the interface, so it doesn't matter whether the actual objects have the method or not.
If the method getAllowedNether must be called very often and you run into performance problems because of that, I will have to think of a more advanced answer. This one should be fine for now.
Reflection API throws NoSuchMethodException when using Class.getMethod(...) functions.
Otherwise Oracle has a nice tutorial about reflection http://download.oracle.com/javase/tutorial/reflect/index.html
In java this is called reflection. The API allows you to discover methods and call them at runtime. Here is a pointer to the docs. It's pretty verbose syntax but it'll get the job done:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
I would use a separate method to handle the exception and have a null check to check if method exists
Ex : if (null != getDeclaredMethod(obj, "getId", null)) do your stuff...
private Method getDeclaredMethod(Object obj, String name, Class<?>... parameterTypes) {
// TODO Auto-generated method stub
try {
return obj.getClass().getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
If you're using Spring in your project you may check ReflectionUtil.findMethod(..). It returns null if method does not exist or does not match your requirements. Documentation.
Roland Illig is correct, but wanted to add in an example of how to check if a method exists that requires a parameter using Class.getMethod. Can also use Class.getDeclaredMethod if you are trying to access a private method.
class World {
public void star(String str) {}
private void mars(String str) {}
}
try {
World.class.getMethod("star", String.class);
World.class.getDeclaredMethod("mars", String.class);
} catch (Exception e) {}
Other solution:
public static <O> boolean existsMethod(final String methodName, final O o) {
return Stream.of(o.getClass().getMethods()).map(Method::getName).anyMatch(methodName::equals);
}