The architecture of my application is like this:
Main classe -> ServiceBean -> Manager -> DAO.
I am throwing an exception in my DAO:
catch (HibernateException he) {
throw new RemuRuntimeLoggableException(he, RuntimeLoggableException.HIBERNATE_UNKNOWN);
}
Then in Manager I catch the exception as below:
catch (RuntimeLoggableException e) {
log.info(e.getMessage());
e.printStackTrace();
throw new RuntimeLoggableException(e, RuntimeLoggableException.HIBERNATE_UNKNOWN);
And in my ServiceBean, I have this:
catch (RuntimeLoggableException e) {
log.info(e.getMessage());
e.printStackTrace();
throw new RemoteException();
In my main class, I have caught the exception like this:
catch (RemoteException e) {
log.info(prefixeLog + " Error");
log.info(e.getMessage());
I also have an interface Service.java. ServiceBean implements this interface and the method concerned here is declared as below in the interface, Service.java:
public void calculate( boolean flag )
throws java.rmi.RemoteException;
The problem I am getting is that the exception RemoteException from the ServiceBean, is not caught in the main class. And I can't modify the interface Service.java as it is automatically generated by XDoclet. Any idea of how to do this please?
In my Service.java, the method is declared like this:
public void calculate( boolean flag )
throws java.rmi.RemoteException;
And in my class it is declared as below:
public static void main(String[] args) throws RuntimeLoggableException {
try {
log.info("Start" + prefixeLog);
serviceBean.calculate(true);
log.info("End" + prefixeLog);
} catch (RemoteException e) {
log.info(prefixeLog + " Error");
log.info(e.getMessage());
}
finally {
InitFramework.stopFramework(FrameworkFacade.BATCH);
System.exit(retour);
}
}
And in my serviceBean:
public void calculate(boolean flagExclurePlansPerimes) throws RemoteException {
You are logging the message of the RemoteException but you are thrown a RemoteException that is constructed without a message.
Related
I was making a command to clear messages using JDA.
I made this code
public class Main {
public static JDA jda;
public static void main(String[] args) throws LoginException {
jda = JDABuilder.createDefault("OTM0ODA4NTY1ODYzMDM5MDA3.Ye1eUg.JExQxPx8UUli8YQfN7TfdbzLHqI").build();
jda.addEventListener(new CommandExecutor());
} }
public class CommandExecutor extends ListenerAdapter {
public static final String prefix = "!-";
public void onMessageReceived(MessageReceivedEvent event) {
String[] args = event.getMessage().getContentRaw().split(" ");
if (args[0].equalsIgnoreCase(prefix + "clear"))
new Clear(event, args);
} }
public class Clear {
public Clear(MessageReceivedEvent event, String[] args) {
try {
int numberOfMessages = Integer.parseInt(args[1]);
List<Message> messages = event.getChannel().getHistory().retrievePast(numberOfMessages + 1).complete();
event.getChannel().purgeMessages(messages);
event.getChannel().sendMessage("Messages have been deleted!").queue(m -> m.delete().queueAfter(5, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
} } }
The code inside the try block will clear the messages if a valid argument is passed. In case an invalid argument is passed, like a string, it should go to the catch block and print the details of the exception. However, this does not happen, and the error gets generated.
Here is the error generated
java.lang.NumberFormatException: For input string: "de"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:668)
at java.base/java.lang.Integer.parseInt(Integer.java:786)
at JDA.TelevisionBot.Commands.Clear.<init>(Clear.java:24)
at JDA.TelevisionBot.CommandExecutor.onMessageReceived(CommandExecutor.java:26)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:359)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:88)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:70)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:164)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:121)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:952)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:839)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:817)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:991)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
Thanks in advance
it is normal that you get everything you indicated since e.printStackTrace(),It's a method on Exception instances that prints the stack trace of the instance to System.err.
It's a very simple, but very useful tool for diagnosing an exceptions. It tells you what happened and where in the code this happened.
try {
throw new NullPointerException();
}
catch (NullPointerException e) {
System.out.println(e);
}
try {
throw new IOException();
}
catch (IOException e) {
e.printStackTrace();
}
System.exit(0);
Calling println(e):
java.lang.NullPointerException
Calling e.printStackTrace():
java.io.IOException
at package.Test.main(Test.java:74)
I'm doing some testing of my stateless session beans from a junit class so the flow goes something like this.
Junit test method calls a business method in bean A. This method throws a CustomException.
Bean A business method calls bean B business method. This method also throws a CustomException.
Bean B calls a remote Bean C which throws a BeanCException. Bean B catches an AccountBadFormatException, wraps it in CustomException and throws is back to Bean A.
From Bean A CustomException is rethrown back to JUnit calling code. When I catch CustomException in JUnit and look at it, there is no AccountBadFormatException inside. The cause reads "CustomException" and the stacktrace is gone. But If I look at it in Bean A just before it gets thrown to JUnit the nested exception is there. Why would this happen?
JUnit class:
#Test
public void testGetResult() {
setupContext();
Result result = null;
try {
result = (Result) serviceInterface.getResult("000001", "01011970");
} catch (CustomException e) {
System.out.println("CustomException getCause() in JUnit: " + e.getCause().toString());
fail();
}
assertTrue((result.getReturnCode() == ReturnCode.OK));
}
Bean A:
#Override
public Result getResult(String clientID, String dob) throws CustomException {
Result result = new Result(ReturnCode.ERROR);
boolean isMatched = false;
try {
isMatched = Lookup.getUtilityService().isIdentMatched(clientID, dob);
} catch (CustomException e) {
System.out.println("CustomException getCause() in Bean A: " + e.getCause().toString());
throw e;
}
if (isMatched) {
result.setReturnCode(ReturnCode.OK);
}
return result;
}
Bean B:
#Override
public boolean isIdentMatched(String clientID, String dob) throws CustomException {
IdentRequest request = new IdentRequest(clientID);
ClientSummary response = null;
// retrieve the data
try {
response = getRetriever().getClientSummaryView(request)
.getClientSummary();
} catch (XrefAccountNumberException e) {
throw new CustomException(e.getMessage(), e);
} catch (AccountNotFoundException e) {
throw new CustomException(e.getMessage(), e);
} catch (AccountBadFormatException e) {
throw new CustomException(e.getMessage(), e);
} catch (ExclusiveLockException e) {
throw new CustomException(e.getMessage(), e);
} catch (RemoteException e) {
throw new CustomException(e.getMessage(), e);
} catch (ValidationException e) {
throw new CustomException(e.getMessage(), e);
}
return response.isMismatch();
}
The output of the print statement in Bean A is: "CustomException getCause() in Bean A: ca.gc.cra.iica.iasi.common.exceptions.AccountBadFormatException"
The print statement in JUnit is: "CustomException getCause() in JUnit: ca.gc.cra.fltr.filemyreturn.business.exceptions.CustomException"
My current code:
class ThrowDemo
{
static void throwMethod()
{
System.out.println("Inside throwMethod");
throw new IllegalAccessException("demo");
}
public static void main(String args[])
{
try
{
throwMethod();
}
catch(IllegalAccessException e)
{
System.out.println("Caught"+e);
}
}
}
Upto my knowledge exception thrown by throwMethod must be caught. But why does IllegalAccessException get thrown by throwMethod not caught by the catch?
I do not know how to successfully try and catch the exception. As you can see I already started the try-catch statement but do not know how to finish it. I get the error " tractorException.java:83: error: unreported exception tractorException; must be caught or declared to be thrown
setVehicleID(0); "
import java.io.*;
import java.util.*;
import javax.swing.*;
public class tractorException extends Exception {
protected int VehicleID;
public int setVehicleID(int VehicleID) throws tractorException {
if (VehicleID <= 0 || VehicleID > 100000) {
throw new tractorException();
} else {
this.VehicleID = VehicleID;
return this.VehicleID;
}
}
public int getVehicleID() {
return this.VehicleID;
}
tractorException() {
setVehicleID(0);
}
public static void main (String[] args) {
try {
throw new Exception("Something went wrong!!");
} catch (Exception e) {
}
Change your main method to:
public static void main (String[] args) {
try {
throw new tractorException(); // infinite loop ensues
} catch (Exception e) {
// this catch doesn't matter
}
}
The infinite loop occurs because tractorException's constructor calls setVehicleID(0), which in turn calls throw new tractorException(), which, as you guessed, calls setVehicleID(0) ... to infinity and beyond.
A function that throws exception must be caught or declared to be thrown. The issue you have with your code is in the line setVehicleID(0); as stated in the error log you posted.
Since setVehicleID() method throws exception, any time you call this function, it must be caught or re-throw. To fix your error, you need to surround this call with try catch:
tractorException()
{
try{
setVehicleID(0);
}
catch( tractorException e ) {
// Do something with error
}
}
try enter this
you cannot call Directly setVehicleID method because it is risky Method
tractorException() {
try{
setVehicleID(0);
}catch(Exception e){
}
}
try
{
if(ruleName.equalsIgnoreCase("RuleName"))
{
cu.accept(new ASTVisitor()
{
public boolean visit(MethodInvocation e)
{
if(rule.getConditions().verify(e, env, parentKeys, astParser, file, cu)) // throws ParseException
matches.add(getLinesPosition(cu, e));
return true;
}
});
}
// ...
}
catch(ParseException e)
{
throw AnotherException();
}
// ...
I need to catch thrown exception in the bottom catch, but I cannot overload method via throws construction. How to do with that, please advice? Thanks
Create custom exception, write try catch block in anonymous class and catch it in your catch block.
class CustomException extends Exception
{
//Parameterless Constructor
public CustomException () {}
//Constructor that accepts a message
public CustomException (String message)
{
super(message);
}
}
now
try
{
if(ruleName.equalsIgnoreCase("RuleName"))
{
cu.accept(new ASTVisitor()
{
try {
public boolean visit(MethodInvocation e)
{
if(rule.getConditions().verify(e, env, parentKeys, astParser, file, cu)) // throws ParseException
matches.add(getLinesPosition(cu, e));
return true;
}
catch(Exception e){
throw new CustomException();
}
});
}
// ...
}
catch(CustomException e)
{
throw AnotherException();
}
As suggested already, an unchecked exception could be used. Another option is to mutate a final variable. Eg:
final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
SomeInterface anonymous = new SomeInterface() {
public void doStuff() {
try {
doSomethingExceptional();
} catch (Exception e) {
exceptionRef.set(e);
}
}
};
anonymous.doStuff();
if (exceptionRef.get() != null) {
throw exceptionRef.get();
}