Java try catch block not catching an exception - java

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)

Related

How to check type of Exception occured in java and call another method accordingly?

I have
public static void main(String[] args){
String text = parseXml(XmlText); // Exception occurs here in called method.
}
I want to check the type of exception occurred while parsing xml and call another method accordingly like this.
if(thisException){
String text = anotherMethod(xmlText);
}
How can I achieve this.
Thanks in advance.
Use a try catch for this
public static void main(String[] args){
try {
String text = parseXml(XmlText);
// do something
}
catch ([THE EXCEPTION TYPE] ex){
String text = anotherMethod(xmlText);
// do something else
}
}
Your application will still crash if the exception is not handled in your catch. You can also catch different types of exceptions and handle them accordingly by adding another catch-clause. E.g.
catch (EXCEPTION1 EX) {
// ...
}
catch (EXCEPTION2 EX) {
// ...
}

remove last method from stacktrace before throwing exception

I have a utility method for timing and logging various queries all over the project.
The problem is, when looking at crashlytics now all unrelated crashes are joined together into one crash-instance.
Can I catch all exceptions on the utility method, and throw them after removing that method from the stack?
The environment is Android (Java)
UPDATE:
based on #Dhananjay's answer below, here's my code:
public static Cursor get(...) {
try {
// my utility code
} catch (RuntimeException e) {
throw cleanException(e);
}
}
private static RuntimeException cleanException(RuntimeException e) {
try {
StackTraceElement[] stackTrace = e.getStackTrace();
StackTraceElement[] subTrace = new StackTraceElement[stackTrace.length - 1];
System.arraycopy(stackTrace, 1, subTrace, 0, subTrace.length);
e.setStackTrace(subTrace);
return e;
} catch (Throwable ignored) {
return e;
}
}
This approach might solve your problem: Set the stacktrace of the exception in the utility logging method to exclude the utility method itself, and then throw the exception, here is a working example, you can modify it to eliminate any StackTraceElement you want to:
package test;
public class TestMain {
public static void main(String args[]) throws Exception {
try {
apiCall();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void apiCall() throws Exception {
logAndThrow();
}
public static void logAndThrow() throws Exception {
Exception e = new Exception();
StackTraceElement[] cleanedUpStackTrace = new StackTraceElement[e.getStackTrace().length -1];
// Eliminate this mehod i.e. logAndThrow's stack trace entry (i.e. the first one) in cleanedUpStackTrace
System.arraycopy(e.getStackTrace(), 1, cleanedUpStackTrace, 0, cleanedUpStackTrace.length);
for(StackTraceElement ste : cleanedUpStackTrace) {
System.out.println(ste.getMethodName());
}
e.setStackTrace(cleanedUpStackTrace);
throw e;
}
}
Here is the output of this program, the logAndThrow method is not present in stack trace now:
apiCall
main
java.lang.Exception
at test.TestMain.apiCall(TestMain.java:33)
at test.TestMain.main(TestMain.java:25)

Catching exception from DAO to the first class calling method,

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.

Properly throwing your own exception (make it not terminate your program)

I have some problems throwing my own exception. Here is the code:
class MyException extends Exception {
private String message;
public MyException(String message) {
this.message = message;
}
#Override
public String toString() {
return "Something went wrong: " + message;
}
}
code where MyException is thrown:
static void expand(String input, String output) throws MyException {
try {
Scanner sc = new Scanner(new File(input));
//do something with scanner
} catch (FileNotFoundException e) {
throw new MyException("File not found!");
}
}
and the main method:
public class Encode {
public static void main(String[] args) throws MyException {
expand("ifiififi.txt", "fjifjif.txt");
System.out.println("ok");
}
the exception is thrown normally, the message is printed normally, but the program is terminated and the "ok" message is not printed out.
Exception in thread "main" Something went wrong: File not found!
at vaje3.Encode.expand(Encode.java:59)
at vaje3.Encode.main(Encode.java:10)
Java Result: 1
You are making life hard on yourself trying to cast a new exception. You dont need to do that, just pass the original up. This is better practice since the FileNotFoundException is a standard error so it is a convention shared by most programmers.
public class Encode {
static void expand(String input, String output)
throws FileNotFoundException
{
Scanner sc = new Scanner(new File(input));//no try catch here or new exception
//just let the original be passed up
//via the throw directive
//Do more here.
}
public static void main(String[] args) {
try{
expand("ifiififi.txt", "fjifjif.txt");
} catch ( FileNotFoundException fnfe ){
System.err.println("Warning File not found");
fnfe.printStackTrace();
}
}
}

I have trouble using the try-catch method for a exception in java

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){
}
}

Categories