Java Exception
Exception handling
Checked exceptions, unchecked exceptions, Errors
Some Exception must not arrive (unckecked exception) but other (from external) must be managed (IOException, FileNotFoundExption)
Common exception classes
- NullPointerException
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ClassCastException
- ….
API java.lang.Throwable
API Class java.lang.Error
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
API Class java.lang.Exception
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
Exercice
1 | class X { |
Which are correct in place of _?
A) blank
B) throws Throwable
C) throws RuntimeException
D) throws IOException
E) throws FileNotFoundException
Responses : B, D, E
FileNotFoundException is a IOException is a Throwable
Exercice
1 | class Base2 { |
Which are true?
A) doBaseStuff in Base2 can be marked throws Exception without causing errors
B) doBaseStuff in Base2 can be marked throws RuntimeException without causing errors
C) doBaseStuff in Sub2 can be marked throws Exception without causing errors
D) doBaseStuff in Sub2 can be marked throws RuntimeException without causing errors
E) if doBaseStuff in Base2 were marked throws Exception,
then doBaseStuff in Sub2 can be marked throws IOException without causing errors
Reponses: A, B, D as RuntimeException is a base Exception, D
Etrange a revoir
Course
Methods must manage restult but also possible failure are their level
Multi Catch Exception from Java 7
Checked Exceptions
- “I dont’ know what to do”
- “I can’t fix that”
“It’s fatal anyway”
So it’s waste of typing
Good desing => Limit consequences of change
When implementation changes, the client is affected => Wrong Design
Encapsulation
What type of failure are acceptable ?
- Depends on the model /abstraction
- Payment Method : Failure can be : No Money, Card Stolen , … or Infrastructure failure
So try to Create New Exception to specify what is the error in design/model point of view (absraction) and regroup exceptions not associated to design