Sunteți pe pagina 1din 8

Java Exception Handling

What is an Exception?

An Exception is an unwanted situation or event that occurs during the execution of a program,
exceptions may lead to termination of the program if not handled properly.
Exceptions in Java?

Whenever an error occurs within a Java code on runtime, an Object is created called Exception
Object, it contains all information about exception including type or class of exception and the
location where the exception is occurred in the program.
Java run time environment searches for an appropriate handler for this exception object, it starts
searching from the current method to calling methods in reverse order and at last the main method.
If an appropriate handler code is found then the exception is handled normally, otherwise program
terminates.
Exception Hierarchy in Java

Throwable is the parent class of all Exceptions that is further extended by two classes, Exception
and Error. In Java Exceptions can be categorized in two main streams:
1) Unchecked Exception
2) Checked Exception

Unchecked Exception

The exceptions that are not checked at compile time are called unchecked exceptions, classes that
extends RuntimeException comes under unchecked exceptions. Examples of some unchecked
exceptions are listed below.
ArithmeticException
Mathematical operations that are not permitted in normal conditions i.e. dividing a number by 0.
package com.beingjavaguys.core;
public class ExceptionTest {
public static void main(String[] args) {
int i = 10/0;
}
}
Console :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:6)
ArrayIndexOutOfBoundsException
Trying to access an index that does not exists or inserting values to wrong indexes results to
ArrayIndesOutOfBound Exception at runtime.
package com.beingjavaguys.core
public class ExceptionTest {
public static void main(String[] args) {
int arr[] = {'0','1','2'};
System.out.println(arr[4]);
}
}
Console :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:7)
NullPointerException
Trying to access a null object or performing operations on an object having a null value.
package com.beingjavaguys.core;
import java.util.ArrayList;
public class ExceptionTest {
public static void main(String[] args) {
String string = null;
System.out.println(string.length());
}
}
Console
Exception in thread "main" java.lang.NullPointerException
at com.beingjavaguys.core.ExceptionTest.main(ExceptionTest.java:9)

Some common Unchecked Exceptions in Java


Here is a list of some common Unchecked Exceptions in Java language.
ArithmeticException
IndexOutOfBoundsException
NullPointerException
NegativeArraySizeException
IllegalArgumentException
ClassCastException
NoSuchElementException
IllegalStateException
ArrayStoreException
CheckedExceptions

Exceptions that are checked at compile-time are called checked exceptions, in Exception hierarchy
all classes that extends Exception class except UncheckedException comes under checked
exception category.
In certain situations Java Compiler force the programmer to write a Exception handler at compile
time, the Exceptions thrown in such situation are called Checked Exception, see the example
below :
try {
String input = reader.readLine();
System.out.println("You typed : "+input); // Exception prone area
} catch (IOException e) {
e.printStackTrace();
}
While writing a code to read or write something from files or even from or to console, a checked
Exception i.e. IOException is thrown, these exceptions are checked at compile time and we are
forced to write a handler at compile time. Thats why we called these exceptions Checked
Exceptions.
Some common CheckedExceptions in Java
Here is a list of some common Checked Exceptions in Java language.
IOException
FileNotFoundException
ParseException
ClassNotFoundException
CloneNotSupportedException
InstantiationException
InterruptedException
NoSuchMethodException
NoSuchFieldException
Whenever an exception is occurred in a Java program, JVM assumes that there is no sense of
keeping the program running until the exception is handled or being thrown to some other piece of
code to handle it. However, in case of Checked Exceptions, Java compiler force the programmer to
write a handling code to deal with exceptions by giving compilation errors.

In java exception handling mechanism is based on following five keywords, lets see these keywords
one by one in detail:
1) try
2) catch
3) finally
4) throws
5) throw
In java most of the handling code is being implemented using try-catch combination with a finally
block added to them.
Let's start our discussion with writing some real exception handling code:
package com.rdayala.exceptions;
public class TryCatchBasicExample {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message"); // this is not printed
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
e.printStackTrace(); // prints stack trace of exception
}
System.out.println("I'm out of try-catch block in Java.");
}
}

A try is the most commonly used keyword of Java Exception handling paradigm, a try block is
one that is used to wrap the exception prone code inside it. If any exception occurs, the control will
go to catch block instantly. Here the thing to note down is that if an Exeption occurs at any code
line of try block, no further code in try block will be executed after that line. Every try block must
have atleast one catch or finally block with it.
'Catch' block is the part of try-catch where we can write code to deal with Exception conditions or
some message or a stack trace of exception object to detect the exception reasons. We can have
more than one catch block per try, each catch block is an exception handler that handles the type of
exception that is being declared as its argument. The argument must be a class name inherited from
Throwable class. As soon as JVM finds exact catch, it will skip all other catch blocks. The
advantage behind having more than one catch is that, sometimes we can not predict which
exception is going to be thrown at run time, so we can provide a list of all expected exceptions in
preceding catch block. General rule is to specify more specialized exception to generalized
exception in catch blocks.
printStackTrace() helps us to find the exact error location and name of method causing the error in
our code. In java every executing program places the details of its invoking methods onto the
execution stack, along with classes and object names and the line number of the code line that is
being executing. Whenever an exception is occurred printStackTrace() can be used to print the
contents of the execution stack, this way the programmer gets the situation in more details and to
the point.

Multiple try-catch in Java

In situation of having more than one catch block, JVM will trace an appropriate catch block from
start and will execute accordingly. As soon as JVM finds exact catch, it will skip all other catch
blocks.
Here one thing to note down is that we must have declared narrow exceptions first and broad one
last, for example Exception class contains all exceptions in it, if we would write a catch with
Exception class first JVM will use that catch and will not reach to exact IOException block.
Here one important thing to note down is that, at a time only one exception is thrown and only one
catch is executed.
A finally block is written followed by a try block or a catch block, code written inside a finally
block is always executed. Sometimes we have situations when a certain piece of code must be
executed, no matters if try block is executed successfully or not, this is what a finally block does
for us.
'throws' keyword in Java

In java if a code written within a method throws an exception, there can be two cases. Either the
code is being enclosed by try block and exception handling is implemented in the same method, or
the method can throws the exception to the calling method simply.
This is what throws does in exception handling, it throws the exception to immediate calling
method in the hierarchy. The throws keyword appears at the end of a method's signature.
public void callingMethod() {
try {
calledMethod(); // here the exception is handled
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void calledMethod() throws IOException{
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
bfr.readLine(); // coz of throws keyword, exception occured here handled by calling method
}
The calling method itself can use a throws keyword and forward the exception to handle by its own
calling method.. so on . This can be forwarded up in the hierarchy, if all calling methods are using
throws and no more calling method is available to handle the exception that the exceptions are
ultimately be handled by main method. And if the main method is also using throws itself, the
exception will be handled by JVM itself.
1) A try block must be followed by a catch or a finally block.
2) A try block can contain any number of catch block, but these catch blocks must represent
distinct Exception Classes that too in narrow to broad order.
3) A catch or finally block can not be used without a try block.
4) There can not be any type of code in between a try, catch and finally blocks

'throw' keyword in Java


In java its possible to throw an exception programmatically , the 'throw' keyword is used to throw
an exception explicitly.
public void saveUserAge(int age) {
if(age<18){
throw new ArithmeticException();
}
else{
System.out.println("Correct are is entered");
}
}
Some Important Points:
1. If nested try-catch block is not handling the exception correctly, the control
will jump to parent try-catch block. If the exception is not handled there also,
then the program will terminate abruptly.
2. All catch blocks must be ordered from most specific to most general i.e. catch
for ArithmeticException must come before catch for Exception.
3. Catch block is not handling the exception thrown in try block. So finally block
is executed and the exception is passed to main thread. Note: The statements
after finally block are not executed.
4. All sub classes of java.lang.Exception except sub classes of RunTimeException are
checked exceptions.
5. Make sure you handle the checked exceptions in try-catch block or include throws
clause at your method declaration. If not handled properly, they will give
compile time error.
6. By default, Unchecked Exceptions are forwarded in calling chain (propagated).
7. By default, Checked Exceptions are not forwarded in calling chain (propagated).
To provide exception propagation for checked exceptions, use throws clause in
method declaration.
8. Java finally block is always executed whether exception is handled or not.
9. If you don't handle exception, before terminating the program, JVM executes
finally block(if any).
10. Even, if try or catch block has a return statement, even then finally block is
executed. finally block overrides return values in try or catch block.
11.

Exceptions and Inheritance


Case 1: Super class methods doesn't declare an exception
Rule 1: If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
Rule 2: If the superclass method does not declare an exception, subclass overridden
method can declare unchecked exception.

Case 2: Super class method declares an exception


Rule: If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent exception.

User-defined Exception
When we do need to write our own exceptions, we should follow the naming convention of
always ending all our class names with "Exception".
Our fields should be final, which is a good rule for most classes to make concurrency
easier.
Our own exception classes should contain more information than just a simple String.

User-defined exception class is so common that it will be used in every project.


1. Extend the Exception class.
2. Provide parameterize constructor
3. Override toString() method.
Example:
class OutOfRangeException extends IllegalArgumentException {
private final long value, min, max;
public OutOfRangeException(long value, long min, long max) {
super("Value " + value + " out of range " + "[" + min + ".." + max
+ "]");
this.value = value;
this.min = min;
this.max = max;
}
public long getValue() {
return value;
}
public long getMin() {
return min;
}
public long getMax() {
return max;
}
//
//
//
//

@Override
public String toString() {
return "Value " + value + " out of range " + "[" + min + ".." + max + "]";
}

}
class Person {
public static final int MIN_AGE = 0;
public static final int MAX_AGE = 150;
private final int age;
private final String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
if (this.age < MIN_AGE || this.age > MAX_AGE) {
throw new OutOfRangeException(this.age, MIN_AGE, MAX_AGE);

}
}
public String toString() {
return "Person " + name + " is " + age + " years old";
}
}
public class UserDefinedException {
public static void main(String[] args) {
try{
Person p1 = new Person(200, "ABC");
}
catch(OutOfRangeException ex) {
System.out.println(ex);
// ex.printStackTrace();
}
}
}

S-ar putea să vă placă și