| ... | ... | @@ -125,3 +125,31 @@ public int view() throws StackIsEmptyException { ... } |
|
|
|
|
|
|
|
:book: La balise `@throws` permet de documenter dans quel cas l'exception est soulevée (une balise par exception)
|
|
|
|
|
|
|
|
# Soulevement des exceptions
|
|
|
|
|
|
|
|
:book: Pour avertir d'une anomalie lors de sa détection, une méthode :
|
|
|
|
- instancie un nouvel objet issu de la classe d'exception appropriée
|
|
|
|
- soulève l'exception explicitement via le mot-clé `throw`
|
|
|
|
|
|
|
|
:book: L’exécution de la méthode s’**arrête immédiatement** et l’exception remonte au code appelant (si la méthode retourne un résultat, le resultat n'existe pas)
|
|
|
|
|
|
|
|
Par exemple, la méthode `push` de la classe `StackOfNonNegativeIntegers` est mise en oeuvre comme suit :
|
|
|
|
|
|
|
|
```java
|
|
|
|
/**
|
|
|
|
* Push an element (on top of stack)
|
|
|
|
* @param element the element to push
|
|
|
|
* @throws StackIsFullException if stack is full
|
|
|
|
* @throws NegativeElementException if element is negative
|
|
|
|
*/
|
|
|
|
public void push(int element) throws StackIsFullException, NegativeElementException {
|
|
|
|
|
|
|
|
if (this.size == this.capacity) throw new StackIsFullException();
|
|
|
|
|
|
|
|
if (element < 0) throw new NegativeElementException();
|
|
|
|
|
|
|
|
this.elements[this.size] = element;
|
|
|
|
this.size += 1;
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|