Try catch not being forced - java

I have this Exception:
public class ErrorException extends Exception
{
private static final long serialVersionUID = 1L;
private String errorMessage = "";
private int errorCode = 0;
private String errorLevel = "";
private Window errorSource = null;
public String getErrorMessage()
{
return errorMessage;
}
public int getErrorCode()
{
return errorCode;
}
public String getErrorLevel()
{
return errorLevel;
}
public Window getErrorSource()
{
return errorSource;
}
public ErrorException(String message, int code, int level, Window source)
{
super();
errorMessage = message;
errorCode = code;
switch (level)
{
case 0:
{
errorLevel = "benignError";
}
case 1:
{
errorLevel = "criticalError";
}
case 2:
{
errorLevel = "terminalError";
}
}
errorSource = source;
}
}
And I have this method:
public static Element check(final Document document) throws ErrorException
{
try
{
chapter.resetLatch();
final SecondaryLoop loop = Toolkit.getDefaultToolkit().getSystemEventQueue().createSecondaryLoop();
new Thread()
{
#Override
public void run()
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
answer.getPreviousElement().takeFocus();
question.removeAnswer(answer);
question.rewriteLetters();
Utils.update(chapter);
loop.exit();
}
});
}
}.start();
loop.enter();
chapter.getLatch().await();
}
catch (InterruptedException e)
{
throw new ErrorException("blankElementDialogError", 8, 1, Main.getGui().getMasterWindow());
}
return new Element();
}
And I use it in this constructor code:
public ConfirmCloseDialog(final Document document, final int postOperation)
{
final CustomJButton doSave = new CustomJButton(Main.getString("doSave"), false);
doSave.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent arg0)
{
getConfirmCloseDialog().dispose();
new Thread()
{
#Override
public void run()
{
/*this method is the one above -->*/Element problem = BlankElementDialog.check(document);
if (problem == null)
{
new SaveChooser(document, postOperation);
}
else
{
new BlankElementDialog(problem);
}
}
}.start();
}
});
}
The code for the second part is not full, but there are no special constructs in the rest of the code (just some GUi objects being constructed and there is no try catch anywhere in the constructor).
However, Eclipse isn't forcing me to encapsulate the method call into try catch block, despite the fact that the method throws an Exception (ErorrException subclasses Exception).
And I know that Exception is checked exception, so it should force it, right?
Why?
What do I have to do so it would force it?

Even without any details Eclipse should notify, look at this:
Just restart the Eclipse should solve the issue.
public class TestClass {
public static void main(String[] args) {
method(2);//Notification here!
}
static void method(int a) throws myException {
}
}
class myException extends Exception {
}

Related

Rxjava crashing in release build with error "java.lang.AbstractMethodError: abstract method void io.reactivex.rxjava3.core.Observer.onSubscribe"

I have written a RxDownloader class to download items from a predefined list. The downloader is working fine when exporting as debug aar(sdk) file but getting crashed in relase build with following stacktrace:-
java.lang.AbstractMethodError: abstract method "void io.reactivex.rxjava3.core.Observer.onSubscribe(io.reactivex.rxjava3.disposables.Disposable)"
at io.reactivex.rxjava3.internal.operators.observable.ObservableSubscribeOn.subscribeActual(ObservableSubscribeOn.java:34)
at io.reactivex.rxjava3.core.Observable.subscribe(Observable.java:13176)
at io.reactivex.rxjava3.core.Observable.subscribeWith(Observable.java:13229)
Following is RxDownloader class code:-
public class RxDownloader {
private static final String TAG = RxDownloader.class.getSimpleName();
private static Scheduler mScheduler;
public static void initRxDownloader() {
mScheduler = Schedulers.newThread();
}
public void downloadFromList( ArrayList<DownloadItemEntity> downloadItemEntities, IDownloadListener iDownloadListener) {
Observable downloadObservable = Observable.fromIterable(downloadItemEntities);
Observer downloadObserver = new Observer() {
#Override
public void onSubscribe(#NonNull Disposable d) {
}
#Override
public void onNext(Object o) {
DownloadItemEntity downloadItemEntity = (DownloadItemEntity) o;
downloadPictureFromURL(downloadItemEntity, iDownloadListener);
}
#Override
public void onError(#NonNull Throwable e) {
}
#Override
public void onComplete() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
};
downloadObservable.subscribeOn(mScheduler).subscribeWith(downloadObserver);
}}
Anyone knows how to resolve this error?

Run method inside a method in java

I'm sending more than 1 request to a web service, below there is an example of that requests. Its important for my application to get the answer from the web service so if there is an exception application will try couple of times to get the answer.
Because of that getting something simple like
deviceList = serviceAdapter.getDevices(); is turn into below code.
boolean flag = true;
int counter = 1;
List<Device> deviceList = null;
while (flag) {
try {
deviceList = serviceAdapter.getDevices();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
}
}
}
And in my application i have lots of requests which means there will be more ugly codes. Is there a way where i will call my request methods as parameter for another method something like this:
deviceList = wrapperMethod(serviceAdapter.getDevices());
Problem is there will be different type of requests, so they will return different type objects (list,array,string,int) and their paramaters will change. Is there a suitable solution in java for this problem?
You can pass a Supplier<T> to the wrapperMethod:
public static <T> T wrapperMethod (Supplier<T> supp) {
boolean flag = true;
int counter = 1;
T value = null;
while (flag) {
try {
value = supp.get();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
}
}
}
}
And call it with:
List<Device> deviceList = wrapperMethod (() -> serviceAdapter.getDevices());
I'm afraid, though, that it will limit the methods you call within the lambda expression to throw only RuntimeExceptions.
You can use some command implementation to execute some specific codes :
Here is a simple example of a command
interface Command{
void run();
}
And a couple of implementations :
class SayHello implements Command{
#Override
public void run() {System.out.println("Hello World");}
}
class KillMe implements Command{
public void run() { throw new RuntimeException();};
}
All we have to do to execute those method is to receive an instance of Command and run the method :
public static void execCommand(Command cmd) {
cmd.run();
}
And to use this
public static void main(String[] args) {
execCommand(new SayHello());
execCommand(new KillMe());
}
Hello World
Exception in thread "main" java.lang.RuntimeException
It also accepts lambda expression :
execCommand(() -> System.out.println("Say goodbye"));
And method reference :
public class Test{
public static void testMe() {
System.out.println("I work");
}
}
execCommand(Test::testMe);
Note that I didn't specify that this could throw Exception so I am limited to unchecked exception like RuntimeException but of course void run() throws Exception could be a solution. That way you can do what ever you want.
Full example (with exceptions) :
public class Test {
public static void main(String[] args) {
try {
execCommand(new SayHello());
execCommand(() -> System.out.println("Say goodbye"));
execCommand(Test::testMe);
execCommand(new KillMe());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void testMe() throws IOException{
System.out.println("I work");
}
public static void execCommand(Command cmd) throws Exception {
cmd.run();
}
}
interface Command{
void run() throws Exception;
}
class SayHello implements Command{
#Override
public void run() {System.out.println("Hello World");}
}
class KillMe implements Command{
public void run() { throw new RuntimeException();};
}
Output:
Hello World
Say goodbye
I work
Exception in thread "main" java.lang.RuntimeException
at main.KillMe.run(Test.java:39)
at main.Test.execCommand(Test.java:25)
at main.Test.main(Test.java:17)
You can use #RetryOnFailure annotation from jcabi-aspects
Create a wrapper method then annotate it to enable auto retry upon Exception
As an example:
#RetryOnFailure(attempts = 5)
List<Device> retryWhenFailed(ServiceAdapter serviceAdapter) throws Exception {
return serviceAdapter.getDevices();
}
This solution uses Generics to be able to handle different Object with most of the same code and a Runnable to execute the fetching.
With this solution, you would need only to write the different adapters extending from ServiceAdapter<T extends Fetchable> to implement the logic to fetch the data for each different class (which would have to implement Fetchable).
Define an interface that abtracts the objects that can be fetched by the different services.
package so50488682;
public interface Fetchable {
}
The ojbect that are to be retrieved implement this interface so you can use the same code for different classes.
package so50488682;
public class Device implements Fetchable{
private String id;
public Device(String id) {
this.id = id;
}
public String toString() {
return "I am device " + id;
}
}
Define an abstract ServiceAdapter that the different service adapters will extend to implement the logic for each kind of object to be retrieved. We add throws Exception to the get() method so this method cand just delegate the exception handling to the FetcherService and decide if it should retry or fail.
package so50488682;
import java.util.List;
public abstract class ServiceAdapter<T extends Fetchable> {
public abstract List<T> get() throws Exception;
}
This is an example of an implementation done to get objects of class Device.
package so50488682;
import java.util.ArrayList;
import java.util.List;
public class DeviceServiceAdapter extends ServiceAdapter<Device>{
#Override
public List<Device> get() throws Exception{
List<Device> rtn = new ArrayList<>();
// fetch the data and put it into rtn, this is a mock
Device d = new Device("1");
rtn.add(d);
d = new Device("2");
rtn.add(d);
d = new Device("3");
rtn.add(d);
//
return rtn;
}
}
Finally this is a generic solution to run the different service adapters.
public class FetcherService<T extends Fetchable> implements Runnable{
List<T> result = new ArrayList<>();
ServiceAdapter<T> serviceAdapter;
#Override
public void run() {
boolean flag = true;
int counter = 1;
while (flag) {
try {
result = serviceAdapter.get();
flag = false;
} catch (Exception e) {
try {
if (counter == 5) {
System.out.println("Timeout Occured!");
flag = false;
} else {
Thread.sleep(1000 * counter);
counter++;
}
} catch (InterruptedException e1) {
throw new RuntimeException("Got Interrupted in sleep", e);
}
}
}
}
public List<T> getResult() {
return result;
}
public void setResult(List<T> result) {
this.result = result;
}
public void setAdapter(ServiceAdapter<T> adapter) {
this.serviceAdapter = adapter;
}
}
From the main or calling program it work like this:
package so50488682;
import java.util.List;
public class SO50488682 {
public static void main(String args[]) {
try {
DeviceServiceAdapter deviceServiceAdapter = new DeviceServiceAdapter();
FetcherService<Device> deviceFetcherService = new FetcherService<>();
deviceFetcherService.setAdapter(deviceServiceAdapter);
deviceFetcherService.run();
List<Device> devices = deviceFetcherService.getResult();
for(Device device : devices) {
System.out.println(device.toString());
}
}catch(Exception e) {
System.out.println("Exception after retrying a couple of times");
e.printStackTrace();
}
}
}

How to write a asynchronous file handler in Vertx

I am new to Vertx.
I am playing with the API and I am trying to write a FileSizeHandler. I don't know if it is the correct way to do it but I would like to have your opinions.
In my code I would like to use the handler like this :
public class MyVerticle extends AbstractVerticle {
#Override
public void start() throws Exception {
getFileSize("./my_file.txt", event -> {
if(event.succeeded()){
Long result = event.result();
System.out.println("FileSize is " + result);
} else {
System.out.println(event.cause().getLocalizedMessage());
}
});
}
private void getFileSize(String filepath, Handler<AsyncResult<Long>> resultHandler){
resultHandler.handle(new FileSizeHandler(filepath));
}
}
Here is my FileSizeHandler class :
public class FileSizeHandler implements AsyncResult<Long> {
private boolean isSuccess;
private Throwable cause;
private Long result;
public FileSizeHandler(String filePath){
cause = null;
isSuccess = false;
result = 0L;
try {
result = Files.size(Paths.get(filePath));
isSuccess = !isSuccess;
} catch (IOException e) {
cause = e;
}
}
#Override
public Long result() {
return result;
}
#Override
public Throwable cause() {
return cause;
}
#Override
public boolean succeeded() {
return isSuccess;
}
#Override
public boolean failed() {
return !isSuccess;
}
}
What bothers me in the handler, is that I have to do it in the constructor of the class. Is there a better way to do it?
First of all, you called your class FileHandler, but it's not. It's a result.
You declare handler in Vert.x like that:
public class MyHandler implements Handler<AsyncResult<Long>> {
#Override
public void handle(AsyncResult<Long> event) {
// Do some async code here
}
}
Now, for what you do, there's vertx.fileSystem():
public class MyVerticle extends AbstractVerticle {
#Override
public void start() throws Exception {
vertx.fileSystem().readFile("./my_file.txt", (f) -> {
if (f.succeeded()) {
System.out.println(f.result().length());
}
else {
f.cause().printStackTrace();
}
});
}
}

Append stacktrace of caller thread into the new thread being created, for easier debugging

I have frequently faced a problem while debugging.
Sometimes a thread ends throwing an exception.
And the reason of that issue is the caller/starter of the thread.
The caller send incorrect parameter or called the thread without initializing something.
In order to find from where the particular thread was called, it takes a little extra effort,
as the stacktrace is useless.
What if we could append the stacktrace of the caller thread into the called thread.
Consider the following example :
public class ThreadTest {
Thread t = new Thread("executeNonBlocking") {
#Override public void run() {
// What would be a good way to
// append callerStackTrace to the stack
// trace of this thread
System.out.println("inside");
new Throwable().printStackTrace();
}
};
public void executeNonBlocking() {
final StackTraceElement[] callerStackTrace = new Throwable().getStackTrace();
new Throwable().printStackTrace();
t.start();
}
public static void main(String[] args) {
new ThreadTest().executeNonBlocking();
}
}
Output
java.lang.Throwable
at ThreadTest.executeNonBlocking(ThreadTest.java:27)
at ThreadTest.main(ThreadTest.java:41)
inside
java.lang.Throwable
at ThreadTest$1.run(ThreadTest.java:34)
Desired output
java.lang.Throwable
at ThreadTest.executeNonBlocking(ThreadTest.java:27)
at ThreadTest.main(ThreadTest.java:41)
inside
java.lang.Throwable
at ThreadTest.executeNonBlocking(ThreadTest.java:27)
at ThreadTest.main(ThreadTest.java:41)
at ThreadTest$1.run(ThreadTest.java:34)
Edit : Here is the solution obtained after discussions with #peter-lawrey
public class StackTraceInheritingThread {
private final Runnable r;
private volatile Thread th = null;
private String title;
private boolean daemon;
private InheritedStackTrace ist ;
private static final ThreadLocal<InheritedStackTrace> tl = new ThreadLocal<InheritedStackTrace>();
public StackTraceInheritingThread(Runnable r) {
this.r = r;
}
private final class StackTraceInheritingUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override public void uncaughtException(Thread t, Throwable e) {
if(ist!=null){
e.addSuppressed(ist);
}
e.printStackTrace(System.err);
}
}
public StackTraceInheritingThread setName(String nm){
this.title = nm;
return this;
}
public StackTraceInheritingThread setDaemon(boolean daemon) {
this.daemon = daemon;
return this;
}
public void start(){
if(th!=null){
throw new IllegalStateException("Already started");
}
th = new Thread(new Runnable() {
#Override public void run() {
tl.set(ist);
r.run();
}
},title);
th.setUncaughtExceptionHandler(new StackTraceInheritingUncaughtExceptionHandler());
if(daemon)th.setDaemon(true);
ist = new InheritedStackTrace();
th.start();
}
public static Throwable getInheritedStackTrace(){
return tl.get();
}
public static StackTraceInheritingThread make(Runnable r1){
return new StackTraceInheritingThread(r1);
}
private static final class InheritedStackTrace extends Exception {
}
public static void main(String[] args) {
StackTraceInheritingThread.make(new Runnable() {
#Override
public void run() {
System.out.println("heelo");
throw new RuntimeException();
}
}).setName("ExperimentalThread").start();
}
}
You can save the Throwable used to create a thread in a thread local variable.
public enum Throwables {
;
private static final InheritableThreadLocal<Throwable> STARTING_THREAD = new InheritableThreadLocal<>();
public static void set(Throwable t) {
STARTING_THREAD.set(t);
}
public static Throwable get() {
return STARTING_THREAD.get();
}
public static void printStartingThrowable() {
Throwable throwable = get();
if (throwable == null) return;
throwable.printStackTrace();
}
public static Thread start(Runnable run, String name, boolean daemon) {
Throwable tmp = new Throwable("Started here");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
set(tmp);
run.run();
}
}, name);
t.setDaemon(daemon);
t.start();
return t;
}
public static void main(String... ignored) {
try {
method();
} catch (Throwable t) {
System.err.println("\nThrown in " + Thread.currentThread());
t.printStackTrace();
printStartingThrowable();
}
start(new Runnable() {
#Override
public void run() {
try {
method();
} catch (Throwable t) {
System.err.println("\nThrown in " + Thread.currentThread());
t.printStackTrace();
printStartingThrowable();
}
}
}, "Test thread", false);
}
private static void method() {
throw new UnsupportedOperationException();
}
}
prints
Thrown in Thread[main,5,main]
java.lang.UnsupportedOperationException
at Throwables.method(Throwables.java:59)
at Throwables.main(Throwables.java:36)
Thrown in Thread[Test thread,5,main]
java.lang.UnsupportedOperationException
at Throwables.method(Throwables.java:59)
at Throwables.access$000(Throwables.java:1)
at Throwables$2.run(Throwables.java:47)
at Throwables$1.run(Throwables.java:26)
at java.lang.Thread.run(Thread.java:744)
java.lang.Throwable: Started here
at Throwables.start(Throwables.java:21)
at Throwables.main(Throwables.java:43)

How to generically implement calling methods stored in a HashMap?

I want to route certain chars to methods, so that when the char is typed in the command-line the method is then executed.
Based on the answer How to call a method stored in a HashMap, I'm mapping these chars to methods by using the "Command" design-pattern.
However I want to generically implement this, so it seems that I need to implement reflection in order to use the Method class as a parameter. My attempt is getting a NullPointerException on the field private Method method in my anonymous class...
Here is my code:
import java.lang.reflect.Method;
public interface InvokesMethod {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
} // end of interface
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
public HashMap<Character, InvokesMethod> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethod>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
this.commands.put(letter, new InvokesMethod() {
// NullPointerException starts here in the stack-trace:
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}).setMethod(method);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
} // end of class
public class Main() {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Regards to your code you didn't initiate method. Bear in mind that execute with null you must call public static method:
Your other issue , you didn't initiated interface properly. Here is working example:
InvokesMethodItf
public interface InvokesMethodItf {
public void invokeMethod() throws Exception;
public void setMethod(Method method);
}
InvokesMethod
public class InvokesMethod implements InvokesMethodItf{
private Method method;
#Override
public void invokeMethod() throws Exception {
method.invoke(null);
}
#Override
public void setMethod(Method method) {
this.method = method;
}
}
Terminal
public class Terminal {
public HashMap<Character, InvokesMethodItf> commands;
public Terminal() {
this.commands = new HashMap<Character, InvokesMethodItf>();
try {
this.setCommand('p',
this.getClass().getDeclaredMethod("printHelloWorld"));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printHelloWorld() {// method.invoke(null) looking for "static" method
System.out.println("Hello World!");
}
private void setCommand(char letter, Method method) {
InvokesMethodItf inv = new InvokesMethod();
inv.setMethod(method);
this.commands.put(letter, inv);
}
public void executeCommand(char letter) throws Exception {
this.commands.get(letter).invokeMethod();
}
}
Main
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
Hello World!
Thanks to #Maxim's original suggestion here, I have an alternate solution by setting the methods as Strings in the HashMap instead --
import java.util.HashMap;
import java.lang.reflect.Method;
public class Terminal {
private HashMap<Character, String> commands;
public Terminal() {
this.commands = new HashMap<Character, String>();
this.commands.put('p', "printHelloWorld");
}
private void printHelloWorld() {
System.out.println("Hello World!");
}
public void executeCommand(char letter) throws Exception {
Method method = getClass().getDeclaredMethod(this.commands.get(letter));
method.invoke(this);
}
public class Main {
public static void main(String[] args) {
Terminal commandLine = new Terminal();
try {
commandLine.executeCommand('p');
} catch (Exception e) {
e.printStackTrace();
}
}
} // end of class
Output:
Hello World!
Now to figure out how to pass parameters to the reflected methods...

Categories

Resources