Content
Exceptions in Java
If an operation cannot be completed due to an error, the program must:
-
return to a stable state and allow other operations
-
try to save your work and finish
This task is difficult because usually the code that detects the error is not the one that can perform such tasks this is why you should inform that you can handle it
The most common solution are the error codes
Java offers another way to deal with errors under exceptional conditions: the exceptions
An exceptional condition is one that prevents the continuation of an operation
It's not known how to handle it, but you can't continue
In Java an exception is thrown to someone who knows how to handle the question in a higher context
In the example it is checked by the conditional if the file readme.txt there was in the system and in case it does not exist it throws the exception IOException, which at the moment is without trying
The reserved word throw terminates the current method and throws an object that provide information about the error that occurred
Normally you would use a class for each type of error
Java requires that a method report the explicit exceptions that it can throw
A method doesn't just have to say it returns if everything goes well; should also indicate what may fail
In the example, we have declared exceptions EOFException and FileNotFoundException affecting the method file
The specification of exceptions is performed using the word throws in the method declaration, and there can be as many as needed separated by a space
Handling of the exceptions
Once detected the error makes it necessary to indicate who is in charge of treating it
An exception handler has the following format:
The block try delimits the group of operations that may produce exceptions
The block catch it is the place to which control is passed if any of the operations throws an exception
In the example it has been used a try block to your catch block to handle the errors of the previous example
If any of the operations in the block throw an exception, the block is interrupted try and runs the catch
At the end of this, it is normally continued
If no exception is thrown, the catch block is ignored
There is also the possibility of using the generic exception Exception, but it is best to use the specific exception type for the error
In the example it has been used a try block to your catch block to handle multiple exceptions as in the previous example
A try block can have multiple catch statements associated
When an exception does not correspond to any catch is propagated backward in the sequence of invocations until a catch right
In the example is managed the exceptions of the methods f1 and f2 and if you don't find any, it continues the execution of the code in the normal way outside of the block try
This example has tried to show the 3 alternatives we can use to handle the exception IOException from the method f2
When a method that throws exceptions is invoked, it is mandatory:
-
to handle the error with a block catch
-
that is indicated by throws its spread
Finally block
There may be occasions in which you want to perform some operation if exceptions occur as if not
Such operations can be located within a finally block
A finally block has the following format:
If there is any exception it will execute the try block and the finally
In the example it has controlled the closing of the file f in the block finaly, always running
If any exceptions occur:
-
If it is caught by a catch the same try it runs east and then the finally
The execution continues after the finally normally
-
If this is not trapped it is running the finally and the exception is propagated to the previous context
Hierarchy of exceptions
Any exception must be an instance of the class Throwable
It inherits the following methods from it:
- getMessage()
returns a string with a message that details of details the exception
- toString()
returns a brief description which is the result is concatenate:
- the name of the class of this object
- el token :
- the result of the method getLocalizedMessage() this object
- fillInStackTrace()
records information about the current state of the stack frames for the current thread
If the stack status cannot be written, there will be no return value
- printStackTrace()
returns the trace that has followed the exception
The first line of output contains the result of the method toString() this object
The remaining lines represent data previously recorded by the method fillInStackTrace()
The basis of the Java exception hierarchy is:
-
Throwable
-
Error
-
Exception
-
RuntimeException
-
-
Derived classes Error describe internal JVM errors:
-
should not be thrown by the classes of user
-
these exceptions rarely occur and when it is the only thing you can do is try to close the program without losing the data
-
Examples: OutOfMemoryError; StackOverflow; etc
Java programs will work with the exceptions of the branch Exception
This group is in turn divided into:
-
The classes that are derived directly from Exception (explicit)
-
Arising from a course of RuntimeException (implicit)
Use the RunTimeException to indicate a programming error
If there is an exception of this type is that fixing the code
Examples:
-
A cast wrong
-
Access to an array out of range
-
Use of a pointer null
The rest of Exception indicate that has happened some error due to any cause beyond the program
Examples:
-
An I/O error
-
Connection Error
Declaration of exceptions
The methods should be declared only with the explicit exceptions
Implicit ones should not be declared (although they can occur equally)
Therefore, when a method declares an exception, warning you that it may occur that error in addition to any error implicit
Creation of exceptions
If you need to handle any errors not covered by the standards that Java has, we can create our own kind of exception
The only condition is that the class derives from Throwable or in any arising out of it
In practice, the following shall generally be derived:
-
of RunTimeException if you want to report a programming error
-
of Exception in any other case
Explicit exceptions | Exceptions implied |
---|---|
Derived from Exception (no de RunTimeException) | Derived from RunTimeException |
Indicate an error external to the application | Indicate a programming error |
If launched it is obligatory to declare them | Don't declare: they are corrected |
If you invoke a method that throws it is compulsory to catch them or declare them to be |
You can catch Otherwise, the application ends |
Exceptions and inheritance
When you redefine a method it is giving another implementation for the same behavior
The new method may only throw exceptions declared in the original method
In the example, has redefined the method f of the class A in the class B with an additional exception
A method can declare the exceptions that do not throw really
A base method may allow the redefinitions may cause exceptions
Constructors, not inherited, can throw new exceptions
Rules of use
-
Standard
-
If an exception can be handle should not be spread
-
It is more convenient to use methods that do not produce errors
-
-
Standard
-
Do not use exceptions to avoid a query
-
Not to abuse them
-
-
-
Standard
-
To separate the error handling logic
All together Separate
-
-
Standard
-
Do not ignore an exception already that we leave the code with errors without control
-