在 try catch 中访问变量

2024-02-28

我在返回 menuFont 行上不断收到编译错误,它表示没有变量 menuFont。有人可以告诉我如何解决这个问题吗?

import java.awt.Font;
import java.awt.FontFormatException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class loadFiles {
Font getFont(){
            try {
                Font menuFont = Font.createFont( Font.TRUETYPE_FONT, new FileInputStream("font.ttf"));

            } catch (FileNotFoundException e) {
                System.out.println("Cant find file.");
                e.printStackTrace();
            } catch (FontFormatException e) {
                System.out.println("Wrong file type.");
                e.printStackTrace();
            } catch (IOException e) {
                System.out.println("Unknown error.");
                e.printStackTrace();
            }
            return menuFont;
    }
}

代码的基本问题是 Font 对象仅在 try 块的持续时间内处于范围内,因此它在方法末尾的 return 语句中不再可用。两种选择:

将变量声明移到 try 块之外:

Font menuFont = null;
try {
    menuFont = Font.createFont(...);
}
catch (...) {

}
return menuFont;

Or, do return Font.creatFont(...)在 try 内部,从而避免了首先需要变量(并且,显然,return null在方法的最后)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 try catch 中访问变量 的相关文章

随机推荐