My code is :

public final class Pixels{
        BufferedImage img=null;
        public int w,h;
        public Pixels(){
         try {
            // Read from a file
            File file = new File("1.jpg");
            img =  javax.imageio.ImageIO.read(file);

        }
        catch (IOException e) { }
       }


public void checkfunction(){
         h=img.getHeight();    //   errorpoint 
         w=img.getWidth();
       
}

Errors:
Exception in thread "main" java.lang.NullPointerException
at test.Pixels.<init> (Pixels.java:17)

Plz suggest my code!!!!!!

I suggest you not to ignore possible exceptions

In your code, you rely on 'read()' method to throw Exception because you do not completely understand the class methods. I believe that the method handles a null File object by returning null. ("If no registered ImageReader claims to be able to read the resulting stream, null is returned. ")

In this case, the file is read without a problem and the 'read()' return null (no file content is read). Then in your 'checkfunction()', it attempts to use null with getHeight(). That's why the NullPointerException is thrown.

What you may need to do is to throw an exception if img is still null after you read the file, or modify your checkfunction() to return 0 if the img is null. Either way, you should provide pre & post conditions in order to explain what should happen...

PS: Do not attempt to handle all possible exceptions. A common sense is that why would you implement your code the way you do if you know that your code will throw exceptions? Implement it the way it should not have any exception unless it is from external causes. Also, there is no correct way to handle all exceptions...

ok i will try it...and thanx for your suggestion

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.