在try catch中访问变量 [英] Accessing variable inside try catch

查看:559
本文介绍了在try catch中访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在返回menuFont行上遇到编译错误,它说没有变量menuFont。有人可以告诉我们如何解决这个问题。

I keep getting a compile error on the return menuFont line it says there is no variable menuFont. Could someone please tell how to fix this.

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语句中不再可用。两个选项:

The basic problem with your code is that the Font object is only in scope for the duration of the try block, so it's no longer available in your return statement at the end of the method. Two options:

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

Move the variable declaration outside the try block:

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

}
return menuFont;

或者,执行返回Font.creatFont(...),因此首先避免了变量的需要(显然,在方法结束时返回null )。

Or, do return Font.creatFont(...) inside the try, thus avoiding the need for the variable in the first place (and, obviously, return null at the end of the method).

这篇关于在try catch中访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆