Unhandled Exception Error in Java even with try-catch

JoeyJohnJo :

I am quite new to Java and started learning on YouTube. To practice GUI Programs, I decided to make my own and am now trying to resize an image to add to a button in my aplication. I searched how to resize images and found some source code online which I decided to test and put in my own program, but when I call the method I get an unreported exception java.io.IOException; must be caught or declared to be thrown error and the IntelliJ IDE says Unhandled exception: java.io.IOException. I have the try-catch blocks in my code, but this still comes up. How can I fix this? Here is some of my code:

Images.java (class with the resizer method I found online) the try-catch I put in myself.

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Images {

    //Image resizer method for scaling images
    void resizeImage(String inputImagePath, String outputImagePath, int scaledWidth, int scaledHeight) throws IOException {
        //reads input image
        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);

        //creates output image
        BufferedImage outputImage = new BufferedImagee(scaledWidth, scaledHeight, inputImage.getType());

        //scales the inputImage to the output image
        Graphics2D g2d = outputImage.createGraphics();

        g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();

        // extracts extension of output file
        String formatName = outputImagePath.substring(outputImagePath.lastIndexOf(".") + 1);

        //writes to output file
        ImageIO.write(outputImage, formatName, new File(outputImagePath));
        try {
            inputFile = null;
            inputImage = ImageIO.read(inputFile);
        }
       catch(IOException e){
           e.printStackTrace();
           System.out.println("image file path is null");
        }
    }
}

GUI.java (where the error appears when I try to call the method). The error appears at plus.resizeImage.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import com.company.Images;

public class GUI extends JFrame {

    //This will be used for dimensions of the window
    private int height, width;

    GUI(int w, int h) {
        super("OS Control");
        setWidth(w);
        setHeight(h);
        setSize(getWidth(), getHeight()); 


        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        setLocationRelativeTo(null);
        setContent();
        setVisible(true);
    }

    //Gets and sets for height and width of window
    public void setHeight(int height) {
        this.height = height;
    }

    public int getHeight() {
        return height;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getWidth() {
        return width;
    }

////////////////////////////////////////////////

    /*Method with the actual contents of the aplication
      i.e buttons, text fields, etc.
    */
    void setContent() {

        //variables used in the methods for ease of changing if needed
        int buttonWidth, buttonHeight;
        int searchBarWidth, searchBarHeight;

        buttonWidth = 200;
        buttonHeight = 100;
        searchBarWidth = 350;
        searchBarHeight = 25;

        //Panel for the two center buttons
        JPanel buttons = new JPanel();
        //flow layout to center horizontally
        buttons.setLayout(new FlowLayout());
        buttons.setBackground(Color.decode("#9E9E9E"));

        JButton mechanicButton = new JButton("Mecanicos");
        mechanicButton.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
        mechanicButton.setFocusable(false);
        mechanicButton.addActionListener(new MechanicButtonEventHandling());
        buttons.add(mechanicButton);

        JButton osButton = new JButton("Ordens de Servico");
        osButton.setPreferredSize(new Dimension(buttonWidth, buttonHeight));
        osButton.setFocusable(false);
        osButton.addActionListener(new OSButtonEventHandling());
        buttons.add(osButton);

        JPanel center = new JPanel();
        //gridbag layout to center vertically
        center.setLayout(new GridBagLayout());
        center.setBackground(Color.decode("#9E9E9E"));
        //combine the two to center horizontally and vertically
        center.add(buttons);

        JPanel search = new JPanel();
        search.setLayout(new FlowLayout());
        search.setBackground(Color.decode("#9E9E9E"));
        search.setSize(new Dimension(getWidth(), searchBarHeight));

        JTextField searchBar = new JTextField("Pesquisar: ");
        searchBar.setPreferredSize(new Dimension(searchBarWidth, searchBarHeight));
        searchBar.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 10));

        search.add(searchBar);

        JPanel plusPanel = new JPanel();
        plusPanel.setLayout(new BorderLayout());
        plusPanel.setSize(new Dimension(10, 10));

        Images plus = new Images();
        plus.resizeImage("plus.png","plusButton.png", 10, 10);
        ImageIcon plusButtonImage = new ImageIcon("plusButton.png");
        JButton plusButton = new JButton(plusButtonImage);
        plusButton.setSize(new Dimension(10, 10));

        plusPanel.add(plusButton, BorderLayout.SOUTH);
        //add to jframe
        add(search);
        add(center);
        add(plusPanel);
    }

    private class MechanicButtonEventHandling implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JFrame mechanicList = new JFrame("Lista de Mecanicos");
            mechanicList.setSize(getWidth(), getHeight());
            mechanicList.setLocation(100, 100);
            mechanicList.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            mechanicList.setVisible(true);
        }
    }

    private class OSButtonEventHandling implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            JFrame osList = new JFrame("Lista de ordens de servico");
            osList.setSize(getWidth(), getHeight());
            osList.setLocation(700, 100);
            osList.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            osList.setVisible(true);
        }
    }
}
akortex91 :

You need to have a better look at how Java handles exceptions.

Your Images#resizeImage method contains a few operations that throw an IOException this being, the ImageIO#read and ImageIO#write calls.

At the bottom of the method's body you do this:

try {
    inputFile = null;
    inputImage = ImageIO.read(inputFile);
} catch(IOException e){
    e.printStackTrace();
    System.out.println("image file path is null");
}

In this code bit you're handling the thrown IOException with a try-catch clause. The same cannot be said though for these calls:

BufferedImage inputImage = ImageIO.read(inputFile);

ImageIO.write(outputImage, formatName, new File(outputImagePath));

Since both of these thrown an exception which is not handled within the method's scope (i.e with a try-catch clause), you're forcing the method's signature to have a throws declaration for the IOException thrown by these two. Since, IOException is a checked exception, the compiler expects to find a try-catch clause wrapping the call to Images#resizeImage method.

To fix your code you have two possible solutions:

Remove the try-catch clause from the method's body, leaving only the throws declaration forcing callers to handle the exception at the calling point.

Wrap almost all of the method's body or the places where an IOException is thrown in try-catch clauses, thus handling the exception within the method's body (not a good idea since this way you'll not know whether the act of resizing failed or not).

It seems that your understanding of how exceptions work and how you need to handle them is a bit limited, so before doing anything else I would suggest to take a small detour and check on them.

https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=160292&siteId=1