在try catch中访问变量

twi*_*ing 6 java try-catch

我一直在返回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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 18

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

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

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

}
return menuFont;
Run Code Online (Sandbox Code Playgroud)

或者,return Font.creatFont(...)在try中进行,从而避免首先需要变量(显然,return null在方法结束时).