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

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();
}
}
}

Related

Java try catch block not catching an exception

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)

Why am I receiving the error: "must be caught or declared thrown java"?

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

Java reflection - Error throw

I have the following code:
class ClassDetails {
private String current_class;
public ClassDetails(String current_class) {
this.current_class = current_class;
}
public void getClassDetails() throws ClassNotFoundException {
try {
Class theClass = Class.forName(current_class);
String name = theClass.getName() ;
System.out.println(name);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
class MMain {
public static void main(String[] args) {
ClassDetails C = new ClassDetails(args[0]);
C.getClassDetails();
}
}
And I have this error in main:
Unhandled exception type ClassNotFoundException
How can I solve this?
Your main method calls the getClassDetails() method, which throws that exception, as the signature shows:
public void getClassDetails() throws ClassNotFoundException
And you aren't catching it, or throwing it in the method, so your code will not compile. So you must either do:
public static void main(String[] args) throws ClassNotFoundException {
ClassDetails C = new ClassDetails(args[0]);
C.getClassDetails();
}
Or:
public static void main(String[] args) {
ClassDetails C = new ClassDetails(args[0]);
try
{
C.getClassDetails();
}
catch(ClassNotFoundException ex)
{
//Add exception handling here
}
}

Why is the main method not covered?

main method:
public static void main(String[] args) throws Exception
{
if (args.length != EXPECTED_NUMBER_OF_ARGUMENTS)
{
System.err.println("Usage - java XFRCompiler ConfigXML PackageXML XFR");
}
String configXML = args[0];
String packageXML = args[1];
String xfr = args[2];
AutoConfigCompiler compiler = new AutoConfigCompiler();
compiler.setConfigDocument(loadDocument(configXML));
compiler.setPackageInfoDoc(loadDocument(packageXML));
// compiler.setVisiblityDoc(loadDocument("VisibilityFilter.xml"));
compiler.compileModel(xfr);
}
private static Document loadDocument(String fileName) throws Exception
{
TXDOMParser parser = (TXDOMParser) ParserFactory.makeParser(TXDOMParser.class.getName());
InputSource source = new InputSource(new FileInputStream(fileName));
parser.parse(source);
return parser.getDocument();
}
testcase:
#Test
public void testCompileModel() throws Exception
{
// construct parameters
URL configFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Config.xml");
URL packageFile = Thread.currentThread().getContextClassLoader().getResource("Ford_2008_Mustang_Package.xml");
File tmpFile = new File("Ford_2008_Mustang_tmp.xfr");
if(!tmpFile.exists()) {
tmpFile.createNewFile();
}
String[] args = new String[]{configFile.getPath(),packageFile.getPath(),tmpFile.getPath()};
try {
// test main method
XFRCompiler.main(args);
} catch (Exception e) {
assertTrue(true);
}
try {
// test args length is less than 3
XFRCompiler.main(new String[]{"",""});
} catch (Exception e) {
//ignore
}
tmpFile.delete();
}
Coverage outputs displayed as the lines from String configXML = args[0]; in main method
are not covered.
assertTrue(true); is a pointless no-op
Remove the try/catch around the call to XFRCompiler.main(args);, since all it does is swallow excpetions and make debugging harder; most likely you will then see an exception that tells you where the problem is.
There should be a call to fail() after the call to XFRCompiler.main(new String[]{"",""}); since you expect it to throw an exception
Put the two calls in separate test methods.
I'm worried about all those assertTrue(true). If there can't be an exception, then the assert is not necessary. If there is an unexpected exception, then this code will swallow it and you will get the behavior you see right now.
Then, if you expect an exception, you should code like this:
try {
... code that will throw an exception ...
fail("No exception was thrown");
} catch (SpecficTypeOfException e) {
assertEquals("message", e.getMessage());
}
That way, wrong types of exception and the exception message will be checked.
PS: Don't post questions with "urgent". We already help as fast as we can.

Categories