Hello,

J'ai 2 questions

Je pense avoir compris le traitement d'une exception grace aux clauses try/catch où l'on assigne un traitement dans le bloc catch en cas d'erreur décelée dans l'exécution du bloc try, mais je ne comprends pas le concept de propagation d'une exception d'une part, et l'utilité de créer des exceptions personnalisées.

Je me suis efforcé de créer un petit exercice qui lève une exception personnalisée ou une ArithmeticException ici :

Exception personnalisée

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package exceptionProjectBis;
 
public class ExceptionDivision {
 
	private int x;
	private int y;
 
	public ExceptionDivision(int x, int y)  {
		super();
		this.x = x;
		this.y = y;
	}
 
	//Une méthode qui lève une exception inclut la clause "throws" et nom_E
	public int diviser() throws DivisionByZeroException {
		if(y==0) throw new DivisionByZeroException();
		int res =  x/y;
		return res;	
	}
 
	public class DivisionByZeroException extends Exception{
 
		public DivisionByZeroException() {
			super();
			// TODO Auto-generated constructor stub
		}
 
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			ExceptionDivision ed = new ExceptionDivision(5, 0);
			System.out.println(ed.diviser());
 
		} catch(DivisionByZeroException e) {
			System.out.println(e.getMessage()+"Erreur ! Division par zéro impossible");
			//e.printStackTrace();
		}
 
		finally {
			System.out.println("Veuillez saisir de nouvelles valeurs");
		}
	}
}
Avec ArithmeticException
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class ExceptionTer {
	private int x;
	private int y;
 
	public ExceptionTer(int x, int y)  {
		super();
		this.x = x;
		this.y = y;
	}
 
	//Une méthode qui lève une exception inclut la clause "throws" et nom_E
	public int diviser() throws ArithmeticException {
		if(y==0) throw new ArithmeticException();
 
		int res =  x/y;
		return res;	
	}
 
	public static void main(String[] args) {
		try {
			ExceptionTer ed = new ExceptionTer(5, 0);
			System.out.println(ed.diviser());
 
		} catch(ArithmeticException e) {
			System.out.println("Erreur");
			//e.printStackTrace();
		}
 
		finally {
			System.out.println("Veuillez saisir de nouvelles valeurs");
		}
	}
}
Par commodité j'ai groupé les différentes classes sur un même script

Merci