0% found this document useful (0 votes)
38 views

Unit3-Part1 (Exception Handling)

The document discusses exception handling in Java. It defines two types of errors - compile-time errors and run-time errors. Compile-time errors are detected by the compiler, while run-time errors occur during program execution. Exceptions are a type of run-time error. The key aspects of exception handling in Java are try, catch, throw, throws and finally keywords. try blocks contain code that may throw exceptions. catch blocks catch specific exceptions. Exceptions can be manually thrown using throw or rethrown to outer catch blocks. Methods that throw exceptions must specify them in throws clauses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Unit3-Part1 (Exception Handling)

The document discusses exception handling in Java. It defines two types of errors - compile-time errors and run-time errors. Compile-time errors are detected by the compiler, while run-time errors occur during program execution. Exceptions are a type of run-time error. The key aspects of exception handling in Java are try, catch, throw, throws and finally keywords. try blocks contain code that may throw exceptions. catch blocks catch specific exceptions. Exceptions can be manually thrown using throw or rethrown to outer catch blocks. Methods that throw exceptions must specify them in throws clauses.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Exception Handling

UNIT-3
2
DEALING WITH ERRORS

 An error may produce an incorrect output or may terminate the execution


of the program abruptly or even may cause the system to crash.

 Errors may broadly be classified into 2 categories:


 Compile-time errors
 Run-time errors.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


3
Compile-time errors

 All syntax errors will be detected and displayed by the java compiler and
therefore these errors are known as compile-time errors.

 most of the errors are due to typing mistakes. The most common problems
are:
 missing semicolons
 missing or mismatch of brackets in classes and methods
 misspelling of identifiers and keywords
 use of undeclared variables and so on

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


4
Run-time Errors

 sometimes, a program may compile successfully and create .class file but
may not run properly. such programs may produce wrong results due to
wrong logic or may terminate due to errors.

 most common run-time errors are:


 dividing an integer by zero
 accessing an element that is out of the bounds of an array
 passing a parameter that is not in a valid range
 converting invalid string to a number and so on

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


5
Exception

 An exception is an error that occurs at run time.


 exception handling is important is that java defines standard exceptions
for common program errors, such as divide-by-zero or an out-of-bound
array index.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


6
Exception handling fundamentals

 java exception handling is managed via 5 keywords: try, catch, throw, throws
and finally (all these are inter related, which means use of one implies the use
of another).
 Program statements that you want to monitor for exceptions are contained
within a TRY block. if an exception occurs within the try block, it is thrown. your
code can catch the exception using CATCH and handle it in some manner.
 system generated exceptions are automatically thrown by the java run-time
systems. To manually throw an exception, use the keyword THROW. In some
cases, an exception that is thrown out of a method must be specified as such
by a THROWS clause.
 Any code that absolutely must be executed upon exiting from a try block is put
in a finally block.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


general form of an exception handling 7
block:
try {
//block of code to monitor the errors.
}
catch(ExceptionType1 obj) {
//exception handler for exception type-1.
}
catch(ExceptionType2 obj) {
//exception handler for exception type-2.
}
//......
finally { Example program in eclipse
//block of code to be executed before try block ends.
}
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS
8
Benefits of exception handling

 To maintain the normal flow of the application.


 Separating Error-Handling Code from "Regular" Code.
 Propagating Errors Up the Call Stack.
 Grouping and Differentiating Error Types.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


9
Types of Exception

 In java, all exceptions are


represented by classes.
 All exception classes are
derived from a class called
Throwable.
 there are 2 direct subclasses of
Throwable: Exception and
Error.
 There are 2 types of
exceptions:
 Checked Exception
 Unchecked Exception

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


10
Checked Exception

 The classes that extend Throwable class except RuntimeException and


Error are known as checked exceptions e.g.IOException, SQLException
etc. Checked exceptions are checked at compile-time.
 a method is throwing a checked exception then it should handle the
exception using try-catch block or it should declare the exception
using throws keyword.
 Example programs (using throws and using try-catch)

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


11
Unchecked Exception

 The classes that extend RuntimeException are known as unchecked


exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.

 Unchecked exceptions are not checked at compile-time rather they are


checked at runtime.

 Example program.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


12
Exceptions enable you to handle
errors gracefully

 exception handler can prevent abrupt program termination.


 Example program

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


13
Using multiple catch clauses

 we can associate more than one catch clause with a try. each catch
must catch a different type of exception.
 Example program
 In multiple catch clauses, a catch clause for a superclass will also match
any of its subclasses.
 if you want to catch exceptions of both superclass type and subclass type,
then put the subclass first in the catch sequence. if you do not, then the
superclass catch will also catch all derived classes.
 if you put the superclass catch first, causes unreachable code. since the
subclass catch clause can never execute. In java, unreachable code
causes a compile-time error.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


14
Nested try blocks

 An exception generated within the inner try block that is not caught by a
catch associated with that try is propagated to the outer try block.
 Example program

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


15
Using THROW keyword

 to throw the exception manually.


 syntax : throw exceptionobj;
 throw always throws an object. so creating an object to exception is
compulsory.
 there are 2 ways to obtain a Throwable object:
 1) using a parameter into a catch clause
 2) creating one with the new operator.
 the flow of execution stops immediately after the throw statement; any
subsequent statements are not executed.
 Example program

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


16
Rethrowing an exception

 An exception caught by one catch can be rethrow so that it can caught


by an outer catch.
 Advantage: allowing multiple handlers access to the exception.
 when you rethrow an exception, it will not be recaught by the same catch
clause. it will propogate to the outer catch.
 to rethrow an exception, use a throw statement inside a catch clause.
 Example program
 Homework: what is printStackTrace() method?

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


17
using THROWS keyword

 if a method generates an exception that it does not handle, it must


declare that exception in a throws clause.
 syntax: re-type metd-name(p-list) throws exception-list { //body }
 exceptions that are subclasses of runtime exceptions don't need to be
specified in a throws list. All other types of exceptions do need to be
declared.
 Example program (file program example).

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


18
using FINALLY

 sometimes you want to define a block of code that will execute when a
try/catch block is left(for example, some actions which may need to
perform before it ends).
 A finally block will be executed whenever execution leaves a try/catch
block, no matter what condition causes it.
 the finally block is also executed if any code within the try block or any of
its catch clauses return from a method.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


19
JAVA built-in exceptions

 NOTE: Java defines several exception classes inside the standard


packagejava.lang.
 List of checked exceptions and list of unchecked exceptions.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


list of Java Unchecked RuntimeException:

ArithmeticException
Exception Description
Arithmetic error, such as divide-by-zero.
20
ArrayIndexOutOfBoundsException Array index is out-of-bounds.

ArrayStoreException Assignment to an array element of an


incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.

IllegalMonitorStateException Illegal monitor operation, such as waiting on an


unlocked thread.
IllegalStateException Environment or application is in incorrect state.

IllegalThreadStateException Requested operation not compatible with current


thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.

NegativeArraySizeException Array created with a negative size.

NullPointerException Invalid use of a null reference.


NumberFormatException Invalid conversion of a string to a numeric format.

SecurityException Attempt to violate security.


StringIndexOutOfBounds Attempt to index outside the bounds of a string.

UnsupportedOperationException
Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS An unsupported operation was encountered.
list of Java Checked Exceptions: 21
Exception Description
ClassNotFoundException Class not found.

CloneNotSupportedException Attempt to clone an object that does not


implement the Cloneable interface.

IllegalAccessException Access to a class is denied.

InstantiationException Attempt to create an object of an abstract class


or interface.

InterruptedException One thread has been interrupted by another


thread.

NoSuchFieldException A requested field does not exist.

NoSuchMethodException A requested method does not exist.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS


22
creating exception subclasses

 in java, exceptions is its ability to handle exceptions that you create which
correspond to errors in your program.
 creating an exception is easy just define a subclass of exception.
 exception class does not define any methods of its own. so it uses
throwable methods. if we want we can override these methods.
 2 commonly used exception constructors are
 1) Exception()---> it has no description
 2) Exception(String s) --> it specify a description of the exception.
 Example program.

Faculty: Mrs.M.Lalitha, Assistant Professor, CSE, GNITS

You might also like