【问题标题】:Unhandled Exception Error in Java even with try-catchJava 中未处理的异常错误,即使使用 try-catch
【发布时间】:2019-06-29 22:03:30
【问题描述】:

我对 Java 很陌生,并开始在 YouTube 上学习。为了练习 GUI 程序,我决定自己制作,现在正在尝试调整图像大小以添加到我的应用程序中的按钮。我搜索了如何调整图像大小并在网上找到了一些源代码,我决定对其进行测试并放入我自己的程序中,但是当我调用该方法时,我得到一个unreported exception java.io.IOException; must be caught or declared to be thrown 错误并且 IntelliJ IDE 显示Unhandled exception: java.io.IOException。我的代码中有try-catch 块,但这仍然出现。我怎样才能解决这个问题?这是我的一些代码:

Images.java(我在网上找到的resizer方法的类)try-catch我自己放的。

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(当我尝试调用该方法时出现错误)。错误出现在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);
        }
    }
}

【问题讨论】:

  • 您处理了底部ImageIO.read 调用抛出的IO 异常,但从未处理过第一个read 调用抛出的IO 异常。因此,您尝试通过将异常向上抛出调用层次结构来解决 - 调用 resize 的人现在必须处理 IO 异常。您目前不处理异常resize throws。还有,由于resize会抛出IO异常,所以不需要捕获第二次read调用的IO异常,只要在调用resize时处理异常即可

标签: java error-handling exception-handling try-catch


【解决方案1】:

您需要更好地了解 Java 如何处理异常。

您的 Images#resizeImage 方法包含一些抛出 IOException this 的操作,ImageIO#readImageIO#write 调用。

在方法主体的底部,您可以这样做:

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

在此代码位中,您使用 try-catch 子句处理抛出的 IOException。这 但是对于这些调用,不能这样说:

BufferedImage inputImage = ImageIO.read(inputFile);

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

由于这两个都引发了一个不在方法范围内处理的异常(即使用 try-catch 子句),因此您强制方法的签名为这些引发的 IOException 声明 throws二。由于IOException 是一个检查异常,编译器希望找到一个包装对Images#resizeImage 方法的调用的try-catch 子句。

要修复您的代码,您有两种可能的解决方案:

从方法体中删除 try-catch 子句,只留下 throws 声明,强制调用者在调用点处理异常。

在 try-catch 子句中包装几乎所有方法体或 IOException 被抛出的地方,从而在方法体中处理异常(这不是一个好主意,因为这样您将不知道该行为是否调整大小是否失败)。

您对异常如何工作以及如何处理它们的理解似乎有点有限,所以在做任何其他事情之前,我建议您绕道而行并检查一下。

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

【讨论】:

  • 非常感谢!我按照您的建议通过在调用点处理异常来修复它。我一定会阅读更多关于异常的内容
  • 如果您觉得这对您有帮助,请务必点赞并将其作为建议的答案。
  • 现在就可以了,虽然我今天创建了这个帐户并且还没有 15 分。再次感谢您
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 2011-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多