Sei sulla pagina 1di 38

Exceptions in Java programming language

Introduction
A Java exception is an object that describes an exceptional (that is, error)
condition that has occurred in a piece of code. When an exceptional condition
arises, an object representing that exception is created and thrown in the
method that caused the error. That method may choose to handle the
exception itself, or pass it on. Either way, at some point, the exception is
caught and processed.
The programs you write can generate many types of potential exceptions, such
as when you do the following:
In Java there are three types of loops:

You issue a command to read a file from a disk, but the file does not exist there.

You attempt to write data to a disk, but the disk is full or unformatted.

Your program asks for user input, but the user enters invalid data.

The program attempts to divide a value by 0, access an array with a subscript that is too
large, or calculate a value that is too large for the answers variable type.

These errors are called exceptions because, presumably, they are not usual
occurrences; they are exceptional. The object-oriented techniques to manage
such errors comprise the group of methods known as exception handling.

Exception handling works by transferring the execution of a program to an


appropriate exception handler when an exception occurs. Lets take an
example program which will do take two numbers from user and print division
result on screen. This might lead to exception condition if denominator is zero.

Java Code
1. import java.util.Scanner;
2.
3. public class DivideExceptionDemo {
4.
5.

public static void main(String[] args) {

6.
7.

//Scanner class is wrapper class of System.in object

8.
9.

Scanner inputDevice = new Scanner(System.in);

10.
11.

System.out.print("Please enter first number(numerator): ");

12.
13.

int numerator = inputDevice.nextInt();

14.
15.
16.
17.

System.out.print("Please enter second number(denominator): ");

18.
19.

int denominator = inputDevice.nextInt();

20.
21.
22.
23.

new DivideExceptionDemo().doDivide(numerator, denominator);

24.
25.

26.
27.
28.
29.

public void doDivide(int a, int b){

30.
31.

float result = a/b;

32.
33.

System.out.println("Division result of "+ a +"/"+b +"= " +result);

34.
35.
36.

37.
38.
39. }

Output
Outputs based on user input combinations:

Handling Exceptions:
There are two ways for handling exception, first catch the exception and take
corrective action or throws exception to the calling method which will forces the
calling method to handle it.
1.

In above program the execution is un-expected and ended in error condition in case of
denominator is zero. We can avoid this by handling exception using try-catch block. Lets update
program for exception handling. Here we will write exception prone code inside try block (guarded
block) and catch block will follow the try block.

Java Code
1. import java.util.Scanner;
2.
3. public class DivideExceptionHandle {
4.
5.

public static void main(String[] args) {

6.
7.

Scanner inputDevice = new Scanner(System.in);

8.
9.

System.out.print("Please enter first number(numerator): ");

10.
11.

int numerator = inputDevice.nextInt();

12.
13.

System.out.print("Please enter second number(denominator): ");

14.
15.

int denominator = inputDevice.nextInt();

16.
17.

new DivideExceptionHandle().doDivide(numerator, denominator);

18.
19.

20.
21.
22.
23.
24.

public void doDivide(int a, int b){

25.

try{

26.
27.

float result = a/b;

28.
29.

System.out.println("Division result of "+ a +"/"+b +"= " +result);

30.
31.

}catch(ArithmeticException e){

32.
33.

System.out.println("Exception Condition Program is ending ");

34.
35.

36.
37.

38.
39. }

Output
Outputs based on user input combination:

2.

When a Java method is going to throw an exception, to indicate that as part of the method
signature throws keyword should be used followed by the exception. It means that the caller of
this method should handle the exception given in the throws clause. There can be multiple
exceptions declared to be thrown by a method. If the caller of that method does not handles the
exception, then it propagates to one level higher in the method call stack to the previous caller and
similarly till it reaches base of the method call stack which will be the javas runtime system. For
this approach we use throws keyword in method declaration which will instructs compiler to handle
exception using try-catch block. When we add throws keyword in divide method declaration
compile time error will be seen as below,

Java Code
1. package exceptiondemo;
2.
3. import java.util.Scanner;
4.
5. public class DivideExceptionThrows {
6.
7.

public static void main(String[] args){

8.
9.

Scanner inputDevice = new Scanner(System.in);

10.
11.

System.out.print("Please enter first number(numerator): ");

12.
13.

int numerator = inputDevice.nextInt();

14.
15.

System.out.print("Please enter second number(denominator): ");

16.
17.

int denominator = inputDevice.nextInt();

18.
19.

try {

20.
21.

new DivideExceptionThrows().doDivide(numerator, denominator);

22.
23.

} catch (Exception e) {

24.
25.

System.out.println("Exception Condition Program is ending ");

26.
27.

28.
29.

30.
31.
32.
33.

public void doDivide(int a, int b) throws Exception{

34.
35.
36.

float result = a/b;

37.

System.out.println("Division result of "+ a +"/"+b +"= " +result);

38.
39.

40.
41. }
42.
43. }

As you can see either we can surround the code with try-catch block or we can
re-throw it to be handled by calling method. In this case we are calling method
from main() method so if we re-throw the exception it would be handled by
JVM. Let us update the code and see output based on input combination

Output
Outputs based on user input combination:

Nested Try-catch block:


The try statement can be nested. That is, a try statement can be inside the
block of another try.Each time a try statement is entered, the context of that
exception is pushed on the stack. If an inner try statement does not have a
catch handler for a particular exception, the stack is unwound and the next try
statements catch handlers are inspected for a match. This continues until one
of the catch statements succeeds, or until all of the nested try statements are
exhausted.If no catch statement matches, then the Java runtime system will
handle the exception. Below is the syntax of nested try-catch block.

Java Code
1. package exceptiondemo;
2.
3. public class NestedTryblockDemo {
4.
5.
6.
7.

public static void main(String[] args) {

8.
9.
10.

try{

11.

//some code which can throw Exception

12.
13.

try {

14.
15.

//Some code which can throw Arithmatic exception

16.
17.

try {

18.
19.

//Some code which can throw number format exception

20.
21.

}catch(NumberFormatException n){

22.
23.

//Number format Exception handling

24.
25.

26.
27.

}catch(ArithmeticException a){

28.
29.

//ArithmeticException Handling

30.
31.

32.
33.

}catch(Exception e ){

34.
35.

//General Exception(SuperClass of all Exception) Handling

36.
37.

38.
39.

40.
41. }

Use of finally block:


When you have actions you must perform at the end of a try...catch sequence,
you can use a finally block. The code within a finally block executes regardless
of whether the preceding try block identifies an Exception. Usually, you use a
finally block to perform cleanup tasks that must happen whether or not any
Exceptions occurred, and whether or not any Exceptions that occurred were
caught. In application where database connection, files are being operated, we
need to take of closing those resources in exceptional condition as well as
normal condition.

Java Code
1. package exceptiondemo;
2.
3.
4.
5. public class TryCatchFinally {
6.
7.

public void Demo() {

8.
9.
10.

try {

11.

// statements to try

12.
13.

} catch (Exception e) {

14.
15.

// actions that occur if exception was thrown

16.
17.

} finally {

18.
19.

// actions that occur whether catch block executed or not

20.
21.

22.
23.

24.
25. }

Summary :
We have learned about how exceptions are generated and various ways of
handling exceptions. Catching exception or propagating exceptions. We have
learned keywords like try, catch, finally, throws and programmatic use of these
keywords.

Types of Exceptions
Introduction
Java is object oriented programming language. Exception is object created at
time of exceptional/error condition which will be thrown from program and halt
normal execution of program. Java exceptions object hierarchy is as below:

All exception types are subclasses of the built-in class Throwable. Thus,
Throwable is at the top of the exception class hierarchy. Immediately below
Throwable are two subclasses that partition exceptions into two distinct
branches. One branch is headed by Exception. This classic used for
exceptional conditions that user programs should catch. This is also the class
that you will subclass to create your own custom exception types. There is an
important subclass of Exception, called RuntimeException. Exceptions of this
type are automatically defined for the programs that you write and include
things such as division by zero and invalid array indexing.
The other branch is topped by Error, which defines exceptions that are not
expected to be caught under normal circumstances by your program.
Exceptions of type Error are used by the Java runtime system to indicate errors
having to do with the runtime environment,itself. Stack overflow is an example

of such an error. This chapter will not be dealing with exceptions of type Error,
because these are typically created in response to catastrophic failures that
cannot usually be handled by your program.
Javas exceptions can be categorized into two types:

Checked exceptions

Unchecked exceptions

Generally checked exceptions are subject to the catch or specify requirement,


which means they require catching or declaration. This requirement is optional
for unchecked exceptions. Code that uses a checked exception will not
compile if the catch or specify rule is not followed.
Unchecked exceptions come in two types:

Errors

Runtime exceptions

Checked Exceptions
Checked exceptions are the type that programmers should anticipate and from
which programs should be able to recover. All Java exceptions are checked
exceptions except those of the Error and RuntimeException classes and their
subclasses.
A checked exception is an exception which the Java source code must deal
with, either by catching it or declaring it to be thrown. Checked exceptions are
generally caused by faults outside of the code itself - missing resources,
networking errors, and problems with threads come to mind. These could
include subclasses of FileNotFoundException, UnknownHostException, etc.
Popular Checked Exceptions:
Name

Description

IOException

While using file input/output stream related exception

SQLException.

While executing queries on database related to SQL syntax

DataAccessException

Exception related to accessing data/database

ClassNotFoundException

Thrown when the JVM cant find a class it needs, because of a command-line error,
aclasspath issue, or a missing .class file

InstantiationException

Attempt to create an object of an abstract class or interface.

Below example program of reading file shows how checked exception should
be handled. Below image shows compile time error due to checked exception
(FileNotFoundException and IO Exception) related to file operation. IDE
suggests either we need to enclose our code inside try-catch block or we can
use throws keyword in method declaration.

We will update the method declaration with throws keyword and calling method
(main method) will have to handle this exception. I will explain file reading part
in detail in file I/O tutorial, here we will concentrate more on exception part.
While running the program we can encounter two types of problems (1) File is
missing or not present, which we are trying to read (2) User does not have
read permission on file, or file is locked by some other user. As we are
expecting two different type of exceptions we have to catch both exceptions or
we can have one catch block which is catching super-class Exception. Below
code shows multiple catch block syntax.

Java Code
1. package exceptiondemo;
2.
3. import java.io.FileInputStream;
4.
5. import java.io.FileNotFoundException;

6.
7. import java.io.IOException;
8.
9. public class CheckedExceptionDemo {
10.
11.

public static void main(String[] args) {

12.
13.

//Below line calls readFile method and prints content of it

14.
15.

String filename="test.txt";

16.
17.

try {

18.
19.

String fileContent = new CheckedExceptionDemo().readFile(filename);

20.
21.

System.out.println(fileContent);

22.
23.

} catch (FileNotFoundException e) {

24.
25.

System.out.println("File:"+ filename+" is missing, Please check file na


me");

26.
27.

} catch (IOException e) {

28.
29.

System.out.println("File is not having permission to read, please check


the permission");

30.
31.

32.
33.

34.
35.
36.
37.

public String readFile(String filename)throws FileNotFoundException, IOEx


ception{

38.
39.

FileInputStream fin;

40.
41.

int i;

42.
43.

String s="";

44.
45.

fin = new FileInputStream(filename);

46.
47.

// read characters until EOF is encountered

48.
49.

do {

50.
51.

i = fin.read();

52.
53.
54.

if(i != -1) s =s+(char) i+"";

55.

} while(i != -1);

56.
57.

fin.close();

58.
59.

return s;

60.
61.

62.
63. }

Output: If test.txt is not found:

Running the program after creating test.txt file inside project root folder

Unchecked Exceptions
Unchecked exceptions inherit from the Error class or the RuntimeException
class. Many programmers feel that you should not handle these exceptions in
your programs because they represent the type of errors from which programs
cannot reasonably be expected to recover while the program is running.
When an unchecked exception is thrown, it is usually caused by a misuse of
code - passing a null or otherwise incorrect argument.
Popular Unchecked Exceptions:
Name

Description

NullPointerException

Thrown when attempting to access an object with a reference variable whose curre
value is null

ArrayIndexOutOfBound

Thrown when attempting to access an array with an invalid index value (either nega
or beyond the length of the array)

IllegalArgumentException.

Thrown when a method receives an argument formatted differently than the method
expects.

IllegalStateException

Thrown when the state of the environment doesnt match the operation being
attempted,e.g., using a Scanner thats been closed.

NumberFormatException

Thrown when a method that converts a String to a number receives a String that it
cannot convert.

ArithmaticException

Arithmetic error, such as divide-by-zero.

We had seen sample program of runtime exception of divide by zero in last


tutorial here we will see other program, which will take user age as input and
grant access if age is more than 18 years. Here user input is expected in
numeric form if user input is other alphabetic then our program will end in
exception condition(InputMismatchException). This exception occurs at run
time. We can decide to handle it programmatically but it is not mandatory to
handle. Runtime exceptions are good to handle using try-catch block and avoid
error situation.

Java Code
1. package exceptiondemo;
2.
3. import java.util.Scanner;
4.
5. public class RunTimeExceptionDemo {
6.
7.
8.
9.

public static void main(String[] args) {

10.
11.

//Reading user input

12.
13.

Scanner inputDevice = new Scanner(System.in);

14.
15.

System.out.print("Please enter your age- Numeric value: ");

16.
17.

int age = inputDevice.nextInt();

18.
19.

if (age>18){

20.
21.

System.out.println("You are authorized to view the page");

22.
23.

//Other business logic

24.
25.

}else {

26.
27.

System.out.println("You are not authorized to view page");

28.
29.

//Other code related to logout

30.
31.

32.
33.
34.

35.
36.
37. }

Output

If User enters non-numeric value, program ends in error/exceptional condition.

Summary:

Loop condition/expression can be true always, which makes our loop infinite. This is bad
programming practice as it might result in memory exception. Below statement is valid but not
good to have in our program.

In terms of Functionality Checked and Unchecked Exception are same.

Checked Exception handling verified during compile time while Unchecked Exception are
mostly programming errors

JDK7 provides improved Exception handling code with catching multiple Exceptions in
one catch block and reduce amount of lines of code required for exception handling.

Custom Exceptions
Introduction

We have talked about how to handle exceptions when theyre produced by


calling methods in Java APIs. Java also lets you create and use custom
exceptionsclasses of your own exception as per application need which will
be used to represent errors. Normally, you create a custom exception to
represent some type of error within your applicationto give a new, distinct
meaning to one or more problems that can occur within your code. You may do
this to show similarities between errors that exist in several places throughout
your code, to differentiate one or more errors from similar problems that could
occur as your code runs, or to give special meaning to a group of errors within
your application.
Its fairly easy to create and use a custom exception. There are three basic
steps that you need to follow. We will explain this by example of bank account
balance. Here we want to have flexi-deposit functionality i.e. when account
balance goes beyond 20k, new deposit will be created.

Define the exception class


You typically represent a custom exception by defining a new class. In many
cases, all you need to do is to create a subclass of an existing exception class:

Java Code
1. package exceptiondemo;
2.
3. public class AccountBalanceException extends Exception {
4.
5.

private float accountBalance ;

6.
7.

public AccountBalanceException(float f){

8.
9.

super();

10.
11.

this.accountBalance =f;

12.
13.

14.
15.

public AccountBalanceException(String message){

16.
17.

super(message);

18.
19.

20.
21.

public float getAccountBalance(){

22.
23.

return accountBalance;

24.
25.

26.
27. }

At a minimum, you need to subclass Throwable or one of its subclasses.


Often,youll also define one or more constructors to store information like an
error message in the object, as shown in lines 6-12. Our exception class
AccountBalanceException has two constructors. One with String argument and
second constructor is having float argument. When you subclass any
exception, you automatically inherit some standard features from the
Throwable class, such as:

Error message

Stack trace

Exception wrapping

Declare that your exception-producing method


throws your custom exception
Using throws keyword we can declare method which might be exception
producing. In order to use a custom exception, you must show classes that call
your code that they need to plan for this new type of exception. You do this by
declaring that one or more of your methods throws the exception. Below is
code for account balance management. AccountManagement class has main()
method and two utility methods addAmount() and createFixDeposit(). Here we
have assumecurrentBalance as Rs. 15000. If account balance goes beyond
Rs. 20000, the amount above 20,000 will be passed to make fix-deposit.

Java Code
1. package exceptiondemo;
2.
3. import java.util.Scanner;
4.
5. public class AccountManagement {
6.
7.

private float currentBalance =15000f;

8.
9.

public static void main(String[] args) {

10.
11.

Scanner inputDevice = new Scanner(System.in);

12.
13.

System.out.print("Please enter amount to add in your balance: ");

14.
15.

float newAmount = inputDevice.nextFloat();

16.
17.

try{

18.
19.

float totalAmount = new AccountManagement().AddAmount(newAmount


);

20.
21.

System.out.println("Total Account Balance = "+ totalAmount);

22.
23.

}catch (AccountBalanceException a){

24.
25.

float fdAmount = a.getAccountBalance() - 20000 ;

26.
27.

System.out.println("Your account balance is more than 20K now, So cre


ating FD of Amount: "+ fdAmount);

28.
29.

new AccountManagement().createFixDeposit(fdAmount);

30.
31.

System.out.println("Account Balance = "+20000);

32.
33.

34.
35.

36.
37.

public float AddAmount(float amount) throws AccountBalanceException{

38.
39.

float total = currentBalance+amount;

40.
41.

if (total>20000){

42.
43.

throw new AccountBalanceException(total);

44.
45.

46.
47.

return total;

48.
49.

50.
51.

public void createFixDeposit(float fxAmount){

52.
53.

//Implimentation of FD creation

54.
55.

56.
57. }

Find the point(s) of failure in your error-producing


method, create the exception and dispatch it using
the keyword throw
The third and final step is to actually create the object and propagate it through
the system. To do this, you need to know where your code needs special
processing in the method. Here, Throwable Instance must be an object of type
Throwable or a subclass of Throwable. There are two ways you can obtain a
Throwable object: using a parameter in a catch clause, or creating one with the

new operator. The flow of execution stops immediately after the throw
statement; any subsequent statements are not executed. The nearest
enclosing try block is inspected to see if it has a catch statement that matches
the type of exception. If it does find a match, control is transferred to that
statement. If not, then the next enclosing try statement is inspected, and so on.
Output of above program based on various input parameters as below,

Summary :

Java provides exception classes for most of the common type of errors as well as provides
mechanism to define custom exception classes.
Three steps to create and use custom exception class (1) Define exception class (2) Declare
exception prone method with throws keyword (3) Check condition to throw new exception object to
be handled by calling method.

Try with resource feature of Java 7


Introduction
Java 7 introduce new language feature called try-with-resource statement.
Generally we see data base connection statement, result-set, File IO streams
etc operated inside try-block because checked exception declared inside it.
Before Java 7, we might write code to close these resources in finally block.
Sample code below explain without this feature (This is valid way to write but
not much readable code)

Java Code

1. package trywithresource;
2.
3. public class TryCatchFinally {
4.
5.

public void Demo() {

6.
7.

try {

8.
9.

// create resource statements

10.
11.

} catch (Exception e) {

12.
13.

// Handle the Exceptions

14.
15.

} finally {

16.
17.

//if resource is not null

18.
19.

try{

20.
21.

//close the resources

22.
23.

}catch (Exception resourceClosingExp){

24.
25.

26.
27.

28.
29.

30.
31. }

We have to explicitly close the resource and thereby add a few more lines of
code. There are few cases where the developer will forget to close the
resource and this will introduce memory leak and performance impact in large
application. So to overcome these and other issues try-with-resources is
introduced in Java 7. To understand the resource handling lets take an
example. Here in below program we are defining two custom exceptions
(ExceptionA and ExceptionB). We also have myResource class which has two
methods doSomeWork() and closeResource(), here both methods throws
checked exceptions which needs to be handled by calling class. We have main
class which is creating object of myResource and calling method
doSomeWork(). Inside finally block it is closing the resource.

Java Code
1. package trywithresource;
2.
3. public class MyResource {
4.
5.

public void doSomeWork(String work) throws ExceptionA{

6.
7.

System.out.println("Doing: "+work);

8.
9.

throw new ExceptionA("Exception occured while doing work");

10.
11.

12.
13.

public void close() throws ExceptionB{

14.
15.

System.out.println("Closing the resource");

16.
17.

throw new ExceptionB("Exception occurred while closing");

18.
19.

20.
21. }

Java Code
1. package trywithresource;

2.
3. public class OldTryDemo {
4.
5.

public static void main(String[] args) {

6.
7.

MyResource res = null;

8.
9.

try {

10.
11.

res = new MyResource();

12.
13.

res.doSomeWork("Writing an article");

14.
15.

} catch (Exception e) {

16.
17.

System.out.println("Exception Message: " + e.getMessage()

18.
19.

+ " Exception Type: " + e.getClass().getName());

20.
21.

} finally {

22.
23.

try {

24.
25.
26.

res.close();

27.

} catch (Exception e) {

28.
29.

System.out.println("Exception Message: " + e.getMessage()

30.
31.

+ " Exception Type: " + e.getClass().getName());

32.
33.

34.
35.

36.
37.

38.
39. }

Output:

As you can see 21 lines in code and readability of code decreased. Now lets
implement the same program using Java 7s try-with-resource construct. For
this we would need a new resource NewResource. In Java 7 a new interface
has been introduced named java.lang.AutoCloseable. Those resources which
need to be closed automatically implement this interface. All the older IO APIs,
socket APIs etc. implement the Closeable interface which means these
resources can be closed.
With Java 7, java.io.Closeable implements AutoCloseable. So everything
works without breaking any existing code.

Java Code
1. package trywithresource;
2.
3. public class NewResource implements AutoCloseable {
4.
5.

String closingMessage;

6.
7.

public NewResource(String closingMessage) {

8.
9.

this.closingMessage = closingMessage;

10.
11.

12.
13.

public void doSomeWork(String work) throws ExceptionA {

14.
15.

System.out.println(work);

16.
17.

throw new ExceptionA("Exception thrown while doing some work");

18.
19.

20.
21.

public void close() throws ExceptionB {

22.
23.
24.

System.out.println(closingMessage);

25.

throw new ExceptionB("Exception thrown while closing");

26.
27.

28.
29.

public void doSomeWork(NewResource res) throws ExceptionA {

30.
31.

res.doSomeWork("Wow res getting res to do work");

32.
33.

34.
35. }

Java Code
1. package trywithresource;
2.
3.
4.
5. public class TryWithResource {
6.
7.

public static void main(String[] args) {

8.
9.

try (NewResource res = new NewResource("Res1 closing")) {

10.
11.

res.doSomeWork("Listening to podcast");

12.
13.

} catch (Exception e) {

14.
15.

System.out.println("Exception: " + e.getMessage() + " Thrown by: "

16.
17.

+ e.getClass().getSimpleName());

18.
19.

20.
21.

22.
23. }

Output:

One thing to note above is that the Exception thrown by the close is being
suppressed. So you can right away notice the difference between the two
implementations, one using trycatchfinally and the other using try-withresource. In the example above only one resource is declared as used. One
can declare and use multiple resources within the try block, also nest these trywith-resources blocks.

Summary :

Try-with-Resource is additional functionality introduce in Java 7 to make code


development easier but it is not mandatory to use, we can continue using try-catch-finally
block as well.

Try-with-Resource will make code more readable which means easy to understand and
manage.

Potrebbero piacerti anche