Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Exception are used in Java to handle errors or any other exceptional event that occurs in the normal flow of program.
There are several way Exception can occur in Java.
1.
2.
3.
4.
Object is null.
Checked exceptions are subclasss of Exception excluding RuntimeException and its subclasses.
2.
Checked Exceptions force programmers to deal with the exception that may be thrown.
3.
When a checked exception occurs in a method, the method must either catch the exception and take the
appropriate action,or pass the exception on to its caller.
Example
Unchecked Exception
1.
2.
Compiler doesnt force the programmers to either catch unchecked exception or declare it in a throws clause.
3.
Programmers may not even know that the exception could be thrown.
4.
5.
Example
ArrayIndexOutOfBounds Exception.
Note*: try clause can not stand without catch or finally block. Any of them is required.
Exception Propagation
It is not required to handle all exception thrown by try block in catch block (As it is not required block). In case catch
block doesnt handle exception thrown by try block, it will be propagated to method where this method was called
from. In case previous method which called this method also doesnt handle it, exception will propagated to previous
method in method stack and it will keep propagating in the same way unless some method handle it. In case none of
method handle it in call stack, exception will reach to bottom and it will be handled by JVM.
Cheat-sheet
Checked exception are those exception which are subtype of Exception class but excluding classes which
extends Runtime exception.
System.exit() is the only way when finally block will not get executed coz in that case JVM will shut down.
Catch block should be order in the form of most specific to most general. Otherwise compiler will complain
for unreachable code.