next up previous
suivant: Tableau extensible monter: Exemple de programme JAVA précédent: Version simple

Gestion d'exception

Cette seconde version gère différents problèmes avec une levée d'exception. Il illustre comment on peut créer une nouvelle classe qui comprend des composants utiles (variable et méthode). Le cas du tableau plein n'est pas traité ici. Il le sera dans la version suivante du programme.

class Bizarre extends Exception{
    String msg;
    Bizarre(String s){
	msg = s;
    }
    void print(){
	System.out.println(msg);
    }
}
    

class Product{
    String nom;
    int ref;
    int qte;
    void print(){
	System.out.print(nom+" "+ref+" "+qte);
    }
    Product(String n, int r, int q){
	nom = n;
	ref = r;
	qte = q;
    }
    Product stocker(int delta)throws Bizarre{
	if (delta < 0)
	    throw new Bizarre("stocker: parametre negatif");
	qte = qte + delta;
	return this;
    }
    Product destocker(int delta)throws Bizarre{
	if (delta < 0)
	    throw new Bizarre("destocker: parametre negatif");
	if (delta > qte)
	    throw new Bizarre("destocker: stock insuffisant");
	qte = qte - delta;
	return this;
    }
}

class Stock{
    Product[] t = new Product[50];
    int nb = 0;
    protected int rechercher(int r){
	for (int i=0; i < nb; i++){
	    if (t[i].ref == r)
		return i;
	}
	return -1;
    }
    Stock referencer(String n, int r) throws Bizarre{
	if (rechercher(r)>-1)
	    throw new Bizarre("referencer: cette reference existe: " + r);
	// si tableau plein?
	t[nb] = new Product(n,r,0);
	nb = nb + 1;       // nb++;
	return this;
    }
    Stock dereferencer(int r) throws Bizarre{
	int indice = rechercher(r);
	if (indice == -1)
	    throw new Bizarre("dereferencer: cette reference n'existe: pas " + r);
	t[indice] = t[nb-1];
	nb = nb - 1;
	return this;
    }
    Stock ajouter(int r, int delta) throws Bizarre{
	int indice = rechercher(r);
	if (indice == -1)
	    throw new Bizarre("ajouter: cette reference n'existe: pas " + r);
	t[indice].stocker(delta);
	return this;
    }
    Stock retirer(int r, int delta) throws Bizarre{
	int indice = rechercher(r);
	if (indice == -1)
	    throw new Bizarre("retirer: cette reference n'existe: pas " + r);
	t[indice].destocker(delta);
	return this;
    }
    void etat(){
	for (int i = 0; i<nb; i++){
	    t[i].print();
	    System.out.println();
	}
    }
}

class Produit2{
    public static void main(String[] arg){
	Stock st = new Stock();
	try{
	    st.referencer("peigne",1001);
	    st.referencer("brosse",999);
	    st.ajouter(1001,100);
	    st.referencer("lime",1003);
	    st.ajouter(1003,50);
	    st.retirer(1001,3);
	    st.etat();
	    st.ajouter(1200,20); // fatal!
	}catch (Bizarre biz){
	    System.out.println("Une erreur en survenue: ");
	    biz.print();
	    System.out.println();
	}
    }
}



Barthelemy Francois 2002-03-07