v-bind例外_例外简介-章 5

本文通过一个TextAdventure游戏示例,介绍了Java中异常处理的基本用法,包括自定义异常类和如何在代码中抛出及捕获异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

v-bind例外

第5章:如何使用异常的示例

由于异常可能对您来说并不新鲜,因此以下是使用异常的非常基本的Text Adventure示例。 仅仅是为了让您了解如何在实际环境中使用它们-当然,我们欢迎您使用它(您几乎不能说“播放”),并且,如果愿意,可以对其进行扩展。


import java.io.IOException; 
import java.util.Scanner; 
public class Chapter5 {
    private static Scanner scanner = new Scanner(System.in);
    /**
     * It should be known, if the light is on or off.
     */
    private static boolean lightIsOn = true;
    private static boolean roomHasLightSwitch = true;
    private static boolean canTalk = true; 
    public static void main(String[] args)
    {
        while(true)
        {
            try
            {
                checkCommand();
            }
            catch(ActionNotPossibleException anpe)
            {
                System.err.println(anpe);
                if(!anpe.getCause().toString().equals(null))
                    System.err.println("\t" + anpe.getCause());
            }
        }
    } 
    /**
     * Checks, what command the user has given.
     * @throws ActionNotPossibleException
     */
    private static void checkCommand() throws ActionNotPossibleException
    {
        String command = scanner.nextLine();  
        if(command.toLowerCase().startsWith("look at"))
        {
            lookAt(command.substring(8));
        }
        else if(command.toLowerCase().startsWith("move switch"))
        {
            moveSwitch();
        }
        else if(command.toLowerCase().startsWith("say"))
        {
            saySomething(command.substring(4));
        }
        else if(command.toLowerCase().startsWith("shout at"))
        {
            shoutAt(command.substring(9));
        }
        else if(command.toLowerCase().startsWith("quit"))
            System.exit(1);
        else System.out.println("Don't know that command.");
    } 
    /**
     * Switch the light on if it's off and off if it's on.
     */
    public static void moveSwitch() throws ActionNotPossibleException
    {
        lightIsOn = !lightIsOn;
        if(roomHasLightSwitch)
        {
            if(lightIsOn) System.out.println("You switched the light on.");
            else System.out.println("You switched the light off.");
        }
        else throw new ActionNotPossibleException("move the light switch","You can't find a light switch.");
    } 
    /**
     * Look at the targeted Object and give a comment about it.
     * @param target
     * @throws ActionNotPossibleNowException
     */
    public static void lookAt(String target) throws ActionNotPossibleException
    {
        if(!lightIsOn) throw new ActionNotPossibleException("look at " + target, "It is dark.");
        else
        {
            System.out.println("You look at the " + target + ". It's boring.\n");
        }
    } 
    /**
     * Say something.
     * @param sentence
     * @throws UnableToSpeakException
     */
    public static void saySomething(String sentence) throws UnableToSpeakException
    {
        if(canTalk)
        {
            System.out.println(sentence + "\n");
        }
        else throw new UnableToSpeakException("Maybe you should shut up sometimes.");
    } 
    /**
     * Shout at someone or something. It is of course one way of saying
     * something (even though a very unfriendly way).
     * @param target
     * @throws UnableToSpeakException
     */
    public static void shoutAt(String target) throws UnableToSpeakException
    {
        try
        {
            lookAt(target);
            System.out.println("You shout: \"SLARTIBARTFAST\" at " + target + ". No reaction.");
        }
        catch(ActionNotPossibleException anpe)
        {
            UnableToSpeakException utse = new UnableToSpeakException("");
            utse.initCause(anpe);
            throw utse;
        }
    }
} 
还有两个例外,我们使用:

/**
 * Our selfdefined Exception "ActionNotPossibleNowException".
 */
class ActionNotPossibleException extends IOException
{
    // This is just to make sure, the compiler compiles without giving a warning.
    // However, if you should continue developing this game, you might want to change
    // the Version UID.
    private static final long serialVersionUID = 1L;
    public ActionNotPossibleException(String action, String reason)
    {
        super("Could not " + action + " now. Reason: " + reason);
    }
} 
/**
 * A second selfdefined Exception "UnableToSpeakException", which is an "ActionNotPossibleException".
 */
class UnableToSpeakException extends ActionNotPossibleException
{
    private static final long serialVersionUID = 1L;
    public UnableToSpeakException(String reason)
    {
        super("speak",reason);
    }
} 
希望您现在对异常是什么以及如何以有效的方式使用它们有所了解。 返回第4章
附加的文件
文件类型:zip Chapter5.zip (1.3 KB,128视图)

翻译自: https://bytes.com/topic/java/insights/750357-introduction-exceptions-ch-5-a

v-bind例外

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值