loading...

Why does this Java code keep throwing Exception in thread "main" at line 8 when line 8 is the declaration for the main method?

PDS OWNER CALIN (Calin Baenen) on January 05, 2020

I have this very basic Java code (19 lines infact): import java.awt.*; import javax.swing.*; import java.awt.Canvas; import java.awt.Image; clas... [Read Full]
markdown guide
 

Java can give warnings like that if it knows that that method is a problem, but doesn't know where in the method the issue is coming from.

A tried and true way of debugging something like this is to simply comment out the entire method body. Then, uncomment one line at a time and try to recompile after uncommenting the line. The method will again throw the error when it reaches the offending statement.

 

Thanks, that helped alot!
But, when I commented out the entire method it still threw that same error....

 

Okay, this tells me that it is that line. The compiler most likely requires anything that can throw an Exception to try and catch it. Could be your issue.

 

From Googling, it seems this may be something that Eclipse does when you have a compile error somewhere in your project.

For one, you must have a public class to run main; you also haven't imported a lot of the classes (ImageIO, BufferedImage). You should fix the compile errors before expecting running the program to work.

 

BufferedImage is a part of awt, however he could remove the bottom two imports since he has all of awt already imported.

 

Yea, but it just helps to do that because I know in the past when I didn't do that it would sometimes complain that I didn't have those classes, so I double down to be safe.

 

What packages are ImageIO and BufferedImage in? I thought they were part of AWT.

 

What it might be is that your class is not declared public but your main method is. You cannot have a larger scope for an enclosed method than the scope of the class itself, and classes are -- by default -- package-private. Try adding public before class and see if that helps.

In Java, each *.java file should contain a single class which is declared public, otherwise it cannot be accessed outside of the file in which it is defined (it's basically unreachable).

 
 

Others have pretty much answered, but another thing is that you should try and catch an exception for ImageIO.read(File) since it can throw an IOException if the file is not found. This will require defining it in a method.

 

Missing ; after ImageIO call on line 7. Prevents line 8 from compiling correctly.

code of conduct - report abuse