【问题标题】:My own Exception doesn't work我自己的异常不起作用
【发布时间】:2017-08-17 06:52:09
【问题描述】:

我写了一个模拟纸牌游戏的程序。 我为卡片的颜色选择了一些值,为卡片的值选择了一些值。

我写了自己的异常,CarteException.java 有两个孩子,CarteValeurException.javaCarteCouleurException.java,这取决于 Carte 初始化时的异常类型

如果颜色的值不在 1 或 4 中,则将抛出 CarteCouleurExeception.java 的异常,对于另一个异常,如果值不是 1 或在 7 和 13 中,则将抛出CarteValeurException.java

这是我的 Carte.java 类代码:

public Carte(int coul, int val) throws CarteException {
    if(coul < 1 || coul > 4) {
        throw new CarteCouleurException("Erreur d'initialisation lors de la création d'une carte.",coul);
    }
    if(val < 1 || (val > 1 && val < 7) || val > 13) {
        throw new CarteValeurException("Erreur d'initialisation lors de la création d'une carte.",val);
    }
    this.couleur = coul;
    this.valeur = val;
}

这是CarteException.java 类的代码:

public class CarteException extends Exception {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    protected String message;

    protected CarteException() {
        this.message = "";
    }

    public CarteException(String chaine) {
        this.message = chaine;
    }

    public String getMessage() {
        return (this.message + " : Erreur non spécifiée de valeur ou de couleur de carte.");
    }
}

最后,在Belote.java 中初始化卡片:

package TP.TP6.Exercice2;

import java.util.Random;
import java.util.Vector;
import java.util.Stack;

import TP.TP5.Exercice1.Question4.Carte;

public class Belote {
    private Stack<Carte> tasDistibution;
    private Vector<Stack<Carte>> mainsJoueurs;
    private Vector<Stack<Carte>> plisJoueurs;

    public Belote() {
        this.tasDistibution = new Stack<Carte>();
        this.mainsJoueurs = new Vector<Stack<Carte>>(4);
        this.plisJoueurs = new Vector<Stack<Carte>>(4);

        for(int i = 0 ; i < 4 ; i++) {
            this.mainsJoueurs.add(i, new Stack<Carte>());
            this.plisJoueurs.add(i, new Stack<Carte>());
        }

    }

    private void initialiserTasDistribution() throws CarteException {
        for (int i = 0; i <= 5; i++) {
            for (int j = 1; j <= 13; j++) {
                try {

                    //Initialisation right here

                    this.tasDistibution.push(new Carte(i,j));
                }
                catch(CarteException CE) {
                    System.err.println("Erreur : " + CE);
                }
            }
        }
    }

    private void couper() {
        Stack<Carte> tas1 = new Stack<Carte>();
        Stack<Carte> tas2 = new Stack<Carte>();

        Random r = new Random();
        int coupe = 1 + r.nextInt(33 - 1);

        for (int i = 0; i < coupe; i++) {
            Carte carte = this.tasDistibution.peek();
            this.tasDistibution.pop();
            tas1.push(carte);
        }

        while (tasDistibution.isEmpty() == false) {
            Carte carte = this.tasDistibution.peek();
            this.tasDistibution.pop();
            tas2.push(carte);
        }

        while (tas1.isEmpty() == false) {
            Carte carte = tas1.peek();
            tas1.pop();
            this.tasDistibution.push(carte);
        }

        while (tas2.isEmpty() == false) {
            Carte carte = tas2.peek();
            tas2.pop();
            this.tasDistibution.push(carte);
        }
    }

    private void melanger(int nbMelange) {
        Carte tabcarte[] = new Carte[32];

        for (int i = 0; i < tabcarte.length; i++) {
            Carte cartesommet = this.tasDistibution.peek();
            this.tasDistibution.pop();
            tabcarte[i] = cartesommet;
        }

        for (int i = 0; i < nbMelange; i++) {
            Random r = new Random();
            int pos1 = 1 + r.nextInt(32 - 1);
            int pos2 = 1 + r.nextInt(32 - 1);

            if (pos1 == pos2) {
                System.out.println("Pas de chance");
            } else {
                Carte temp;
                temp = tabcarte[pos1];
                tabcarte[pos1] = tabcarte[pos2];
                tabcarte[pos2] = temp;
            }
        }

        for (int i = 0; i < tabcarte.length; i++) {
            Carte carte = tabcarte[i];
            this.tasDistibution.push(carte);
        }
    }

    private void donnerCartesAJoueur(int nbcartedonnes, int numjoueur) {
        for (int i = 0; i < nbcartedonnes; i++) {
            Carte carte = this.tasDistibution.peek();
            this.tasDistibution.pop();
            Stack<Carte> stack = this.mainsJoueurs.get(numjoueur);
            stack.push(carte);
            this.mainsJoueurs.set(numjoueur, stack);
        }
    }

    private void distribuer() {
        for (int i = 0; i < 4; i++) {
            this.donnerCartesAJoueur(3, i);
        } 

        for (int i = 0; i < 4; i++) {
            this.donnerCartesAJoueur(2, i);
        }

        for (int i = 0; i < 4; i++) {
            this.donnerCartesAJoueur(3, i);
        }


        for (int i = 0; i < 4; i++) {
            System.out.println("\n\nDistribution pour joueur : " + (i+1) + " \n\nMain du joueur : " + (i+1));
            System.out.println(this.mainsJoueurs.get(i).toString());
        }
    }

    private void assemblerPlisJoueur() {
        for (int i = 0; i < 4; i++) {
            while (this.plisJoueurs.get(i).isEmpty() == false) {
                Carte carte = this.plisJoueurs.get(i).peek();
                Stack<Carte> stack = this.plisJoueurs.get(i);
                stack.pop();
                this.plisJoueurs.set(i, stack);
                this.tasDistibution.push(carte);
            }
        }
    }

    private void preparerPremiereManche() throws CarteException {
        try {
            this.initialiserTasDistribution();
        }
        catch(CarteException CE) {
            System.err.println("Erreur d'initilisation du tas à distribuer.");
            throw CE;
        }
        this.melanger(32);
        this.couper();
        this.distribuer();
    }

    private void preparerMancheSuivante() {
        this.assemblerPlisJoueur();
        this.couper();
        this.distribuer();
    }

    private void jouerPli() {
        Stack<Carte> tasIntermediaire = new Stack<Carte>();

        for (int i = 0; i < 4; i++) {
            Carte carte = this.mainsJoueurs.get(i).peek();
            Stack<Carte> stack = this.mainsJoueurs.get(i);
            stack.pop();
            this.mainsJoueurs.set(i, stack);
            tasIntermediaire.push(carte);
        }

        Random r = new Random();
        int gagnant = 0 + r.nextInt(4 - 0);
        System.out.println("Le joueur " + (gagnant+1) + " a gagné ce pli");

        for (int i = 0; i < 4; i++) {
            Carte carte = tasIntermediaire.peek();
            tasIntermediaire.pop();
            Stack<Carte> stack = this.plisJoueurs.get(gagnant);
            stack.push(carte);
            this.plisJoueurs.set(gagnant, stack);
        }
        System.out.println("Pli du joueur " + (gagnant+1));
        System.out.println(this.plisJoueurs.get(gagnant).toString());
    }

    private void jouerManche(int nbPlis) {
        for (int i = 1; i <= nbPlis; i++) {
            System.out.println("\n\nPli numéro : " + i);
            this.jouerPli();
        }
        this.preparerMancheSuivante();
    }

    public void jouerPartie(int nbManches) throws CarteException {
        try {
            this.preparerPremiereManche();
        }
        catch(CarteException CE) {
            System.err.println("Erreur d'initialisation de la première manche");
            throw CE;
        }
        for (int i = 1; i <= nbManches; i++) {
            System.out.println("\n\nManche numéro : " + i);
            this.jouerManche(8);
        }
        System.out.println("Jeu terminé");
    }
}

问题出在Belote.java,Eclipse 在这里向我发送这样的错误catch(CarteException CE)

CarteException 无法到达的 catch 块。 try 语句体永远不会抛出这个异常

但我说对了:public Carte(int coul, int val) throws CarteException 在头等舱所以不明白这个问题。

我编写了 CarteValeurException.javaCarteCouleurException.java 类,但这实际上与 CarteException.java 相同,所以我不把类的代码放在这里。

感谢您的帮助!

【问题讨论】:

  • 你能从 Belote.java 中添加你调用initialiserTasDistribution 的代码吗?
  • 只需从 'private void initialiserTasDistribution() throws CarteException' 中删除 Throws CarteException
  • @Slimu 添加了来自Belote.java的完整代码
  • 伙计,无论你是什么国籍,请用英文编码。我的眼睛在流血。 (@Michael 我们走了 :))
  • 你的代码在 Intellij IDEA 中编译得很好。也许这是 Eclipse 的一个设置,它不是发出警告,而是抛出编译异常?

标签: java exception


【解决方案1】:

你必须抛出或捕获你的异常。

你的方法的签名是:

private void initialiserTasDistribution() throws CarteException 

因此,当 Carte 中的构造函数抛出异常时,您的方法会重新抛出异常。因此,catch 是无法到达的。您必须为您的代码选择最佳方法。 这里有一套经验法则:Throws or try+catch

【讨论】:

    【解决方案2】:

    您的问题是您的方法被声明为将异常传播到调用堆栈的更高层:

    private void initialiserTasDistribution() throws CarteException {
    

    这意味着调用方法initialiserTasDistribution 的人将不得不处理这个异常(或者做同样的事情并将它传播得更高)。这是一种推迟责任的形式。它的意思是“我不会处理这个错误,其他人可以”。

    这直接与您的方法的实现相矛盾,因为您确实实际上处理了错误。

    try {
        this.tasDistibution.push(new Carte(i,j));
    }
    catch(CarteException CE) {
        System.err.println("Erreur : " + CE);
    }
    

    如果您更改方法签名以删除 throws 声明,您应该没问题:

    private void initialiserTasDistribution() {
    

    【讨论】:

    • 好的,现在我明白了我的错误,但问题并没有解决,而是我删除了第二次抛出 .. 也许 Eclipse 中的编译设置有问题?
    • 这似乎是可能的。无论有没有我建议的更改,您的代码确实为我正确编译。我建议您对项目进行全面清理和重建。
    • 好的,这肯定是 Eclipse,我在第二台 PC 上尝试了我的程序,它运行良好.. 仍然需要您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    相关资源
    最近更新 更多