exception handling in java - wordpress.com€¦ · syntax errors - compilation errors. ... catch:...

31
Exception Handling in Java An Object oriented Way for Handling Errors

Upload: lamnhi

Post on 03-Jul-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Exception Handling in JavaAn Object oriented Way for Handling Errors

Page 2: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

An Exception is an event, which occurs during theexecution of a program, that disrupts the normal flowof the program's Instructions.

This is one of the powerful feature of Java to handlerun time error and maintain normal flow of javaapplication.

It is common to make mistakes while developing as well as typing a program.

Such mistakes are categorised as:

syntax errors - compilation errors.

semantic errors– leads to programs producing unexpected outputs.

runtime errors – most often lead to abnormal termination of programs or even cause the system to crash.

Page 3: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Dividing a number by zero.

Accessing an element that is out of bounds of an array.

Trying to store incompatible data elements.

Using negative value as array size.

Trying to convert from string data to a specific data value (e.g., converting string “abc” to integer value).

File errors: opening a file in “read mode” that does not exist or

no read permission

Opening a file in “write/update mode” which has “read only” permission.

Corrupting memory: - common with pointers

3

Page 4: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

LinkageError

Error

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Many more classes

Many more classes

Many more classes

IllegalArgumentException

System errors are thrown by

JVM and represented in the

Error class. The Error class

describes internal system

errors. Such errors rarely

occur.

Exception describes

errors caused by your

program and external

circumstances. These

errors can be caught

and handled by your

program.

Page 5: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Handling Exception means transferring execution ofprogram to appropriate handler when an exception occurs.We can handle exception by using try catch block.

try: try is used to define block of code where exceptioncan occur.

catch: catch is used to match specific type of exception.There could be more than one catch clause for one tryblock.

finally: finally determine block of code which will alwaysexecute after try block. Even in case of Exception.

throw: throw keyword is used to throw an exceptionexplicitly.

throws: is a keyword in java language which is used tothrow the exception which is raised in the called methodto it's calling method throws keyword always followed bymethod signature.

Page 6: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

try Block

Statements that causes

an exception

catch Block

Statements that

handle the exception

Throws

exception

Object

Page 7: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

7

Exception

"thrown" here

Exception

handler

Exception

handler

Thrown exception matched against

first set of exception handlers

If it fails to match, it is matched

against next set of handlers, etc.

If exception matches none of

handlers, program is abandoned

Page 8: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

8

Preceding step

try block

throw

statement

unmatched catch

matching catch

unmatched catch

next step

Page 9: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

ArithmeticException

ArrayIndexOutOfBoundException

ArrayStoreException

FileNotFoundException

IOException – general I/O failure

NullPointerException – referencing a null object

OutOfMemoryException

SecurityException – when applet tries to perform an action not allowed by the browser’s security setting.

StackOverflowException

StringIndexOutOfBoundException

9

Page 10: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

without Exception Handling Exception Handling

class ExceptionDemo {

public static void main(String[] args)

{

int a=10,

ans=0;

ans=a/0; System.out.println("Denominator not be zero");

}

}

class ExceptionDemo {

public static void main(String[] args) {

int a=10, ans=0;

try

{

ans=a/0;

}

catch (Exception e)

{

System.out.println("Denominator not be

zero");

} } }

Abnormally terminate program and give a

message like below, this error message is

not understandable by user so we convert

this error message into user friendly error

message, like "denominator not be zero".

Output:

Output:

Denominator not be zero

Program does not reach here

Program reaches here

Page 11: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

When the JVM encounters an error such asdivide by zero, it creates an exceptionobject and throws it – as a notificationthat an error has occurred.

If the exception object is not caught andhandled properly, the interpreter willdisplay an error and terminate theprogram.

If we want the program to continue withexecution of the remaining code, then weshould try to catch the exception objectthrown by the error condition and thentake appropriate corrective actions. Thistask is known as exception handling.

Page 12: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

try and catch block

try block Inside try block we write the block of statements which

causes executions at run time in other words try blockalways contains problematic statements.

Each and every try block must contains at least one catchblock. But it is highly recommended to write multiple catchblocks for generating multiple user friendly error messages.

One try block can contains another try block that is nestedor inner try block can be possible.

catch block Inside catch block we write the block of statements

which will generates user friendly error messages.

Catch block will execute exception occurs in tryblock.

You can write multiple catch blocks

At a time only one catch block will execute out ofmultiple catch blocks.

Page 13: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception
Page 14: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Checked Exception are the exception which checkedat compile-time. These exception are directly sub-class of java.lang.Exception class. Checked exceptionare checked by the compiler at compile-time.

e.g. FileNotFoundException, NumberNotFoundExceptionetc.

Un-Checked Exception are the exception bothidentifies or raised at run time. These exception aredirectly sub-class of java.lang.RuntimeExceptionclass. In real time application mostly we can handleun-checked exception. Un-checked means notchecked by compiler and are checked at run-time notcompile time.

e.g.ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

Page 15: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Checked Exception Classes Un-Checked Exception Classes

FileNotFoundException

ClassNotFoundException

IOException

InterruptedException

ArithmeticException

ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

NumberFormateException

NullPointerException

NoSuchMethodException

NoSuchFieldException

Page 16: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Exception Example

ArithmeticException

ArrayIndexOutOfBoundsException

StringIndexOutOfBoundsException

NumberFormatException

NullPointerException

NoSuchMethodException This exception will be raised whenever

calling method is not existing in the

program.

FileNotFoundException In case the file is missing, the following

output is produced:

Divide by

zero

exception

Page 17: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Programs can throw an exception explicitly.

throw ThrowableInstance;

The exception must be of type

java.lang.Throwable class or it’s sub classes.

Primitive types, such as int or char, as well as

non-Throwable classes, such as String and

Object, cannot be used as exceptions.

There are two ways you can obtain a

Throwable object: using a parameter in a

catch clause, or creating one with the new

operator

Page 18: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

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 no matching catch is found, then the

default exception handler halts the program

and prints the stack trace.

Page 19: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

How to throw an already defined exception using throw keyword

class AgeValidator

{

static void validateStudent(int age){

try {

if(age<5)

throw new ArithmeticException("age to play more");

else

System.out.println("welcome to school");

}

catch (ArithmeticException e)

{

System.out.println(e);

}

}

public static void main(String args[])

{

validateStudent(4);

}}

Page 20: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

class ThrowDemo {

static void demoproc() {

try {

throw new NullPointerException("demo");

} catch(NullPointerException e) {

System.out.println("Caught inside demoproc.");

}

}

public static void main(String args[])

{

demoproc();

}

}

Page 21: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

class Exception2{

static int sum(int num1, int num2){

try

{

if (num1 == 0)

throw new ArithmeticException("First parameter is not valid");

else

System.out.println("Both parameters are correct!!");

}

catch (ArithmeticException e)

{

System.out.println(e);

}

return num1+num2;

}

public static void main(String args[]){

int res=sum(3,12);

System.out.println(res);

System.out.println("Continue Next statements");

}

}

Page 22: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

If a method is capable of causing an exceptionthat it does not handle, it must specify thisbehavior so that callers of the method can guardthemselves against that exception.

A throws clause lists the types of exceptions thata method might throw.

This is necessary for all exceptions, except thoseof type Error or RuntimeException, or any of theirsubclasses.

type method(args-list) throws exception-list

{

// body of method

}

exception-list is a comma-separated list of theexceptions that a method can throw.

Page 23: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

class ThrowsDemo {

static void throwOne() throws IllegalAccessException

{

System.out.println("Inside throwOne.");

throw new IllegalAccessException("demo");

}

public static void main(String args[]) {

try {

throwOne();

}

catch (IllegalAccessException e) {

System.out.println("Caught " + e);

}

}}

O/P:

Inside throwOne

Caught java.lang.IllegalAccessException: demo

Page 24: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception
Page 25: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

class ThrowExample1 {

void mymethod(int num) throws ArithmeticException, ClassNotFoundException{

if(num==1)

throw new ArithmeticException("Number is one");

else

throw new ClassNotFoundException("Number is not one");

}

}

class ThrowExample{

public static void main(String args[]){

try{

ThrowExample1 obj=new ThrowExample1();

//obj.mymethod(2);

obj.mymethod(1);

}

catch(Exception ex)

{

System.out.println(ex);

}

}

}

Page 26: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Built-in exception classes handle somegeneric errors.

For application-specific errors define yourown exception classes.

Define a subclass of Exception:

class MyException extends Exception { … }

MyException need not implement anything –its mere existence in the type system allowsto use its objects as exceptions.

If any exception is design by the user knownas user defined or Custom Exception

Page 27: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

User defined exception-Example

Page 28: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception
Page 29: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Defining Your Own Exceptions

To define your own exception you must do the following:

Create an exception class to hold the exception data.

Your exception class must subclass "Exception" or another

exception class

Note: to create unchecked exceptions, subclass the

RuntimeException class.

Minimally, your exception class should provide a constructor

which takes the exception description as its argument.

To throw your own exceptions:

If your exception is checked, any method which is going to

throw the exception must define it using the throws keyword

When an exceptional condition occurs, create a new instance

of the exception and throw it.

Page 30: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

finally block Java finally block is a block that is used to execute

important code such as closing connection, stream etc.

Java finally block is always executed whether exception is

handled or not.

Java finally block must be followed by try or catch block.

Writing finally block is optional.

Page 31: Exception Handling in Java - WordPress.com€¦ · syntax errors - compilation errors. ... catch: catch is used to match specific type of exception. ... Checked exception

Write a program for finding a Sum of Valid Integer Values

Passed as Command Line Parameters by leaving Invalid

data from the Command Line.

(Hint: use NumberFormatException).

Create a custom exception class named LowGpaException

extended from the class Exception. This class should

contain a constructor with no parameter to call the

Exception class constructor with the message “Your GPA is

not sufficient to apply for this job (2.5)”.

Write a program to implement the following

ArithmeticException

StringIndexOutOfBoundsException

ArrayIndexOutOfBoundsException