| ... | @@ -87,3 +87,41 @@ public class EmptyStackException extends Exception {} |
... | @@ -87,3 +87,41 @@ public class EmptyStackException extends Exception {} |
|
|
public class NegativeElementException extends Exception {}
|
|
public class NegativeElementException extends Exception {}
|
|
|
```
|
|
```
|
|
|
|
|
|
|
|
|
# Signalement des exceptions
|
|
|
|
|
|
|
|
:book: **Toute méthode soulevant une exception doit obligatoirement le signaler** dans sa signature via le mot-clé `throws`.
|
|
|
|
|
|
|
|
:pencil: ne s'applique pas aux sous-classes de `Error` et `RuntimeException` (exceptions dites _non contrôlées_)
|
|
|
|
|
|
|
|
Par exemple, les méthodes `push`, `pop` et `view` de la classe `StackOfNonNegativeIntegers` deviennent les suivantes :
|
|
|
|
|
|
|
|
```java
|
|
|
|
/**
|
|
|
|
* Pushes 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 {...}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Pops (removes and return) an element (from top of stack)
|
|
|
|
* @return the element popped
|
|
|
|
* @throws StackIsEmptyException if stack is empty
|
|
|
|
*/
|
|
|
|
public int pop() throws StackIsEmptyException { ... }
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the element on top of stack (without removing it)
|
|
|
|
* @return the element on top of stack
|
|
|
|
* @throws StackIsEmptyException if stack is empty
|
|
|
|
*/
|
|
|
|
public int view() throws StackIsEmptyException { ... }
|
|
|
|
```
|
|
|
|
|
|
|
|
:bulb: Les constantes liées aux codes de retour des méthodes disparaissent, la méthode `push` ne retourne plus de valeur car les erreurs étant notifiées avec des exceptions.
|
|
|
|
|
|
|
|
:book: Si plusieurs exceptions peuvent être soulevées par la même méthode, leurs noms sont séparés par une `,`.
|
|
|
|
|
|
|
|
:book: La balise `@throws` permet de documenter dans quel cas l'exception est soulevée (une balise par exception)
|
|
|
|
|