This question already has answers here:
Catching nullpointerexception in Java [closed]
(5 answers)
Closed 2 years ago.
I have the code below and I am trying to catch an exception and print out something if the file == null so it doesn't throw an exception but I am having problems solving this.
public class Controller {
private ImageWindow IW = new ImageWindow(this);
private Model M = new Model(this.IW);
private File file = null;
public void openImage() {
File file = IW.ChooseImageFile();
if (file != null) {
M.loadImage(file);
}
this.IW.setVisible(true);
}
public static void main(String[] args) throws IOException {
SwingUtilities.invokeLater(() -> new Controller());
}
}
Usually I would use a try/catch statement for exception management in Java. Reference
try {
Enter code here
} catch (NullPointerException npe) {
System.out.println(“Error Message”);
}
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 1 year ago.
I was working on a program, a basic one that is based on command line input. I made a custom exception which should be triggered when users don't enter the second input, but whenever I do so, it throws array out of bound exception. What should I do in this situation?
package com.company;
public class Program2 {
public static void main(String[] args) throws MYex{
{
int a,b,c;
try
{
a=Integer.parseInt(args[0]); // getting data
b=Integer.parseInt(args[1]); // from command line
if( args[1]==null){
throw new MYex();
}
try
{
c=a/b;
System.out.println("Quotient is "+c);
}
catch(ArithmeticException ex)
{
System.out.println("Error in division !");
}
}
catch (MYex e){
System.out.println(e.toString());
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array out of bound!");
}
finally
{
System.out.println("End of the progarm!!!");
}
}
}}
class MYex extends Exception{
#Override
public String toString() {
return " oops a Exception occured";
}
}
If the user passes only one argument the args array has only one element. Therefore the exception already occurs when you try to access args[1].
To prevent this check args.length before accessing args[1]:
a=Integer.parseInt(args[0]); // getting data
if (args.length == 1) {
throw new MYex();
}
b=Integer.parseInt(args[1]); // from command line
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I am working on a JDA Discord Bot and everytime I run it, I get this exception.
java.lang.NullPointerException: Cannot read the array length because "<local3>" is null
at com.houseofkraft.handler.CommandHandler.scanIndex(CommandHandler.java:42)
at com.houseofkraft.core.DiscordBot.<init>(DiscordBot.java:68)
at com.houseofkraft.Stratos.main(Stratos.java:13)
I was attempting to make a basic Command Handler and here is the code for it:
public void scanIndex(Index index) throws IOException, InvalidLevelException {
String[] commandList = index.indexClass;
for (String classPath : commandList) {
if (classPath.startsWith("com.houseofkraft")) {
String[] classPathSplit = classPath.split("\\.");
String commandName = classPathSplit[classPathSplit.length-1].toLowerCase();
commandPaths.put(commandName, classPath);
DiscordBot.logger.log("Added " + commandName + " / " + classPath + " to path.", Logger.DEBUG);
}
}
}
Index.java:
package com.houseofkraft.command;
public class Index {
public String[] indexClass;
public String[] getIndexClass() {
return indexClass;
}
public Index() {
String[] indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
}
}
I'm not exactly sure why it causes the Exception. Thanks!
EDIT: Here is my DiscordBot Code
public DiscordBot() throws IOException, ParseException, LoginException, InvalidLevelException {
try {
if ((boolean) config.get("writeLogToFile")) {
logger = new Logger(config.get("logFilePath").toString());
} else {
logger = new Logger();
}
logger.debug = debug;
info("Stratos V1");
info("Copyright (c) 2021 houseofkraft");
info("Indexing commands...");
// Add the Commands from the Index
commandHandler.scanIndex(new Index()); // here is the part that I call
info("Done.");
info("Connecting to Discord Instance...");
jda = JDABuilder.createDefault(config.get("token").toString()).addEventListeners(new EventHandler(commandHandler)).build();
if (jda != null) {
info("Connection Successful!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
You have a member variable public String[] indexClass in your Index class. In your constructor you create a new variable with
String[] indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
This way your member variable stays uninitialized. Change the code in the constructor to
this.indexClass = {
"com.houseofkraft.command.Ping",
"com.houseofkraft.command.Test"
};
BTW, the member variable should be private, not public, since you want to access it by getter (and than do access it by the getter in the CommandHandler).
This question already has answers here:
How can I throw CHECKED exceptions from inside Java 8 lambdas/streams?
(18 answers)
Closed 4 years ago.
I have a task to "move" my throws Exception from main() to lambda-expression. That means that when exception occurs in Lambda, the program uses throws from main. The problem is that I can't create any other interface which could automatically do that, because my teacher said to use only interface from java.util.Function and I've been looking in the internet, but mostly there are answers like "create new interface".
public static void main(String[] args) throws IOException {
Function<String, List<String>> flines = (String x) -> {
Stream<String> streamString = Files.lines(Paths.get(x)); //Should throw Exception from main if IOException
List<String> tmp = streamString.collect(Collectors.toList());
return tmp;
};
You can only throw a unchecked exception as Function doesn't declare any checked exception in the signature of its functional interface.
So you can only explicitly throw a RuntimeException (and its subclasses) instances from the lambda body such as :
Function<String, List<String>> flines = (String x) -> {
try{
Stream<String> streamString = Files.lines(Paths.get(x));
List<String> tmp = streamString.collect(Collectors.toList());
return tmp;
}
catch (IOException e){
throw new RuntimeIOException(e);
}
};
But declaring throws IOException in the main() method is so helpless as it will never be thrown it but if you catch the runtime exception in the Function client and that then you re-throw a IOException. But that is a lot of things for almost nothing.
You can catch the IOException inside the lambda expression, wrap it in a RuntimeException, catch that exception in the main, extract the wrapped IOException and throw it:
public static void main(String[] args) throws IOException
{
Function<String, List<String>> flines = (String x) -> {
List<String> tmp = null;
try {
Stream<String> streamString = Files.lines(Paths.get(x));
tmp = streamString.collect(Collectors.toList());
} catch (IOException ioEx) {
throw new RuntimeException (ioEx);
}
return tmp;
};
try {
List<String> lines = flines.apply ("filename.txt");
}
catch (RuntimeException runEx) {
if (runEx.getCause () instanceof IOException) {
throw (IOException) runEx.getCause ();
}
}
}
This question already has answers here:
What is the advantage of chained exceptions
(7 answers)
Closed 5 years ago.
i was reading about Throwable class from https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html but i was not able to understand the chained exception facility. so somebody can please help me in this.
As Oracle doc says
Chained Exception Facility
It is common for Java code to catch one exception and throw another
And an example here from TutorialsPoint:
public class Main{
public static void main (String args[])throws Exception {
int n = 20, result = 0;
try {
result = n/0;
System.out.println("The result is"+result);
} catch(ArithmeticException ex) {
System.out.println ("Arithmetic exception occoured: "+ex);
try {
throw new NumberFormatException(ex);
} catch(NumberFormatException ex1) {
System.out.println ("Chained exception thrown manually : "+ex1);
}
}
}
}
Basically, I am trying to generate a log file in Robocode, but I am having issues as you cannot use try/catch in Robocode (as far as I am aware). I have done the following:
public void onBattleEnded(BattleEndedEvent e) throws IOException
{
writeToLog();
throw new IOException();
}
and
public void writeToLog() throws IOException
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new IOException();
}
and am getting the following error at compile time:-
MyRobot.java:123: onBattleEnded(robocode.BattleEndedEvent) in ma001jh.MyRobot cannot implement onBattleEnded(robocode.BattleEndedEvent) in robocode.robotinterfaces.IBasicEvents2; overridden method does not throw java.io.IOException
public void onBattleEnded(BattleEndedEvent e) throws IOException
^
1 error
As you can see here, the interface doesn't declare any checked exceptions. So you can't throw one in your implementing class.
One way to solve this would be to implement your method like this:
public void onBattleEnded(BattleEndedEvent e)
{
writeToLog();
throw new RuntimeException(new IOException());
}
public void writeToLog()
{
//Create a new RobocodeFileWriter.
RobocodeFileWriter fileWriter = new RobocodeFileWriter("./logs/test.txt");
for (String line : outputLog)
{
fileWriter.write(line);
fileWriter.write(System.getProperty("line.seperator"));
}
throw new new RuntimeException(new IOException());
}
but I am having issues as you cannot use try/catch in Robocode (as far as I am aware)
Where did this assumption came from? I just because of your question here installed robocode (so it's your fault if I'll answer here less often in future), wrote my own robot and it can catch exceptions quite good:
try {
int i = 1/0;
}
catch(ArithmeticException ex) {
ex.printStackTrace();
}
And why are you throwing IOExceptions in your example?