Java Exception overviewDefinition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
The situations that cause exceptions fall into four broad categories: (Java Exception tutorial)Code or Data Errors For example, you attempt an invalid cast of an object, you try to use an array index that's outside the limits for the array, or an integer arithmetic expression that has a zero divisor. Standard Method Exceptions For example, if you use the substring() method in the String class, it can throw a StringIndexOutOfBoundsException exception. Throwing your own Exceptions
We'll see later in this chapter how you can throw a few of your own when you need to. Java Errors These can be due to errors in executing the Java Virtual Machine which runs your compiled program, but usually arise as a consequence of an error in your program. Types of Exceptions (Java Exception tutorial) Error ExceptionsThe exceptions that are defined by the class Error, and its subclasses, are characterized by the fact that they all represent conditions that you aren't expected to do anything about and, therefore, you aren't expected to catch them. There are three direct subclasses of Error - ThreadDeath, LinkageError, and VirtualMachineError. RuntimeException Exceptions The subclasses of RuntimeException defined in the standard package java.lang are:
ArithmeticException An invalid arithmetic condition has arisen such as an attempt to divide an integer value by zero. IndexOutOfBoundsException You've attempted to use an index that is outside the bounds of the object it is applied to. This may be an array, a String object, or a Vector object. The class Vector is defined in the standard package, java.util. NegativeArraySizeException You tried to define an array with a negative dimension. NullPointerException You used an object variable containing null, when it should refer to an object for proper operation - for example, calling a method or accessing a data member. ArrayStoreException You've attempted to store an object in an array that isn't permitted for the array type. ClassCastException You've tried to cast an object to an invalid type - the object isn't of the class specified, nor is it a subclass, or a superclass, of the class specified. IllegalArgumentException You've passed an argument to a method which doesn't correspond with the parameter type. SecurityException Your program has performed an illegal operation that is a security violation. This might be trying to read a file on the local machine from an applet. IllegalMonitor StateException A thread has tried to wait on the monitor for an object that the thread doesn't own. IllegalStateException You tried to call a method at a time when it was not legal to do so. Unsupported OperationException Thrown if you request an operation to be carried out that is not supported.
Dealing with Exceptions (Java Exceptions tutorial)Specifying the Exceptions a Method Can Throwdouble myMethod() throws IOException, FileNotFoundException { // Detail of the method code... }
Handling Exceptions- A try block encloses code that may give rise to one or more exceptions. Code that can throw an exception that you want to catch must be in a try block.
- A catch block encloses code that is intended to handle exceptions of a particular type that may be thrown in a try block.
- The code in a finally block is always executed before the method ends, regardless of whether any exceptions are thrown in the try block.
How try and catch WorkA try statement is used to enclose a block of code in which an exception may occur. Each try statement can have one or more associated catch "clauses" that provide for handling exceptions. A catch clause declares a variable that must be of the class Throwable or a subclass of Throwable. This variable can be used in the code block associated with the catch. The general form is as follows: try { code_block }catch( ExceptionType varname ){ optional code which can use varname }
An eample of try-catch-finally try { // Code that may throw exceptions... } catch(ExceptionType1 e) { // Code to handle exceptions of type ExceptionType1 or subclass } catch(ExceptionType2 e) { // Code to handle exceptions of type ExceptionType2 or subclass ... // more catch blocks if necessary } finally { // Code always to be executed after try block code }
How try and finally Work without catch A try with finally is a perfectly reasonable way to ensure that a particular piece of code will always be executed no matter what happens inside the try block, as shown in the following code: try { // lots of possible returns and exceptions here } finally { // statements that must be executed here } |