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

module 4 -exception handling notes

The document compares abstract classes and interfaces in Java, highlighting their differences in method declaration, instance variables, and inheritance. It also covers exception handling in Java, detailing the types of exceptions, the structure of try-catch blocks, and the use of keywords like throw, throws, and finally. Additionally, it discusses custom exceptions, chained exceptions, and new features such as try-with-resources.

Uploaded by

kenkaneki6120
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

module 4 -exception handling notes

The document compares abstract classes and interfaces in Java, highlighting their differences in method declaration, instance variables, and inheritance. It also covers exception handling in Java, detailing the types of exceptions, the structure of try-catch blocks, and the use of keywords like throw, throws, and finally. Additionally, it discusses custom exceptions, chained exceptions, and new features such as try-with-resources.

Uploaded by

kenkaneki6120
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Abstract class vs interface

Abstract class contains abstract and non- Interfaces do not contain non-abstract
abstract methods. methods but it contains only abstract
methods

Abstract methods contains instance variables Interfaces do not contain instance variables, it
and constants. contains only constants.

Abstract methods needs to be declared as All methods are implicitly public and abstract.
abstract explicitly.

Class needs to be declared abstract explicitly. Interface is abstract implicitly.

Abstract class can extends another class, not An interface can extends another interfaces
interfaces only, not classes

An abstract class can implement an interface An interface cannot implement another


interface or class.

Ex: Ex:

abstract class A{ } interface Bounceable

Exception Handling
1. The Java programming language uses exceptions to handle errors and other exceptional
events.
2. An exception is an abnormal condition that arises in a code sequence at run time.
3. In other words, an exception is a run-time error.
4. In Java, an exception is an object.
5. Exceptions can be generated by
- the Java run-time system, or
- they can be manually generated by our code.

JAVA UNIT - III Page 31


6. Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.

General form of an exception-handling block


try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
// cleanup code
}
Points:
1) Each try statement requires at least one catch or a finally clause..
2) Multiple catch statements can be associated with a single try block
3) finally block is optional. But, finally block always executes after try/catch block
completes.

Exception Types / Exception Hierarchy

All exceptions are subclasses of Throwable class.


Throwable class has two sub-types: 1) Error and 2) Exception
Exception class has a subclass called RuntimeException
User-defined exceptions can be created by extending Exception class.

JAVA UNIT - III Page 32


Exception Types (Built-in Exceptions)
There are two types of exceptions:
1) Checked exceptions
2) Unchecked exceptions

1) Checked Exceptions
These are exceptional conditions that a well-written application should anticipate and
recover from.
Checked exceptions must follow the requirement - Catch or declare the exception
using throws.
Ex: java.io.FileNotFoundException.
All exceptions are checked exceptions, except for those indicated
by Error, RuntimeException, and their subclasses.

CloneNotSupportedException Attempt to clone an object that does not implement


the Cloneable interface.

IllegalAccessException Access to a class is denied.

JAVA UNIT - III Page 33


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.

ReflectiveOperationException Superclass of reflection-related exceptions

2) Unchecked Exceptions
Errors and runtime exceptions are collectively known as unchecked exceptions.
Unchecked exceptions need not follow the requirement - Catch or declare the
exception using throws.
Error:
These are exceptional conditions that are external to the application, and that the
application usually cannot anticipate or recover from.
Ex: An application successfully opens a file for input, but is unable to read the file because
of a hardware or system malfunction.

Runtime Exception:
These are exceptional conditions that are internal to the application, and that the
application usually cannot anticipate or recover from.
These usually indicate programming bugs, such as logic errors or improper use of an
API.
Ex: NullPointerException

ArithmeticException Arithmetic error, such as divide-by-zero.

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.

JAVA UNIT - III Page 34


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.

StringIndexOutOfBoundsException Attempt to index outside the bounds of a string.

Methods in Throwable
Throwable fillInStackTrace( ) Returns a Throwable object that contains a completed
stack trace. This object can be rethrown.

String getMessage( ) Returns a description of the exception.

void printStackTrace( ) Displays the stack trace.

String toString( ) Returns a String object containing a description of the


exception. This method is called by println( ) when
outputting a Throwable object.

Propagating Uncaught Exceptions call stack


class ExceptionTest1 {
public static void main (String [] args) {
doStuff();
}
static void doStuff()
{
doMoreStuff();
}
static void doMoreStuff()

JAVA UNIT - III Page 35


Unhandled or uncaught
exceptions will be handled by
default handler provided by
{ JVM.
int x = 5/0;
} Call stack:
}
Call stack is the sequence of methods
which led to the error

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionTest1.doMoreStuff(ExceptionTest1.java:11)
CALL STACK
at ExceptionTest1.doStuff(ExceptionTest1.java:7)
at ExceptionTest1.main(ExceptionTest1.java:3)

Example for Exception Handling using try/catch/finally

class ExcExample{
public static void main(String args[]) {
try {
int a = args.length;
System.out.println("a = " + a);
int b = 42 / a;
int c[] = { 1 };
c[42] = 99;
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index oob: " + e);
}
finally
{
System.out.println("In finally block.");
}

System.out.println("After try/catch/finally blocks.");


}
}

Nested Try
A try statement can be inside the block of another try. This is called as Nested Try
statement.

JAVA UNIT - III Page 36


If an inner try statement does not have a catch handler for a particular exception, the
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 run-time system will handle the exception.

// An example of nested try statements.


class NestTry {
public static void main(String args[]) {
try {
int a = args.length;

/* If no command-line args are present, the following statement will


generate a divide-by-zero exception. */

int b = 42 / a;
System.out.println("a = " + a);

try { // nested try block


/* If one command-line arg is used, then a divide-by-zero
exception will be generated by the following code. */

if(a==1)
a = a/(a-a); // division by zero

/* If two command-line args are used,then generate an out-of-


bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
}
catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}

throw
It is possible for the program to throw an exception explicitly, using the throw statement.
The general form of throw is shown here:

JAVA UNIT - III Page 37


throw ThrowableInstance;
Here, ThrowableInstance must be an object of type Throwable or a subclass of
Throwable.
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed.

// Demonstrate throw.
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[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}

throws clause

that callers of the method can guard themselves against that exception.

throws
type method-name(parameter-list) throws exception-list
{
// body of method
}

JAVA UNIT - III Page 38


//Example for throws demo
class ThrowsDemo {
static void demoproc() throws IllegalAccessException{
throw new IllegalAccessException("demo");
}
public static void main(String args[]) throws IllegalAccessException
{
demoproc();
}
}

throw vs throws
throw throws

Java throw keyword is used to explicitly Java throws keyword is used to declare
throw an exception. an exception

Checked exception cannot be propagated Checked exception can be propagated


using throw only. with throws.

Throw is followed by an instance. Throws is followed by class.

Throw is used within the method. Throws is used with the method signature

You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws
IOException,SQLException

finally

1) finally creates a block of code that will be executed after a try /catch block has
completed and before the code following the try/catch block.
2) The finally block will execute whether or not an exception is thrown.
3) If an exception is thrown, the finally block will execute even if no catch statement
matches the exception.

JAVA UNIT - III Page 39


4) Any time a method is about to return to the caller from inside a try/catch block, via an
uncaught exception or an explicit return statement, the finally clause is also executed
just before the method returns.

// Demonstrate finally
class FinallyDemo {
// Throw an exception out of the method.
static void procA() {
try {
System.out.println("inside procA");
throw new RuntimeException("demo");
}
finally {
System.out.println("procA's finally");
}
}
// Return from within a try block.
static void procB() {
try {
System.out.println("inside procB");
return; Output:
}
finally { inside procA
System.out.println("procB's finally"); procA's finally
} Exception caught
} inside procB
// Execute a try block normally. procB's finally
static void procC() { inside procC
try { procC's finally
System.out.println("inside procC");
}
finally {
System.out.println("procC's finally");
}
}
public static void main(String args[]) {
try
{
procA();
}
catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procC();
}
}

JAVA UNIT - III Page 40


Custom / User-defined Exception (Creating our Own
Exception Subclasses)
To create a custom exception, program just need to define a class that extends Exception
class.
// This program creates a custom exception type.
class MyException extends Exception {
public String toString() {
return "MyException - Custom Exception";
}
}
class CustomExcDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException();
System.out.println("Normal exit"); Output:
}
Called compute(1)
public static void main(String args[]) { Normal exit
try { Called compute(20)
compute(1); Caught MyException - Custom
compute(20); Exception
}
catch (MyException e) {
System.out.println("Caught " + e);
}
}
}

Chained Exceptions
The chained exception feature allows us to associate another exception with an
exception.
To allow chained exceptions, two constructors and two methods were added to
Throwable.
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc):
The chained exception methods supported by Throwable are:
getCause( ) and
initCause( ).

JAVA UNIT - III Page 41


// Example for Chained Exceptions
import java.io.*;
class ChianedExceptionDemo {
static void compute()
{
ArithmeticException ae = new ArithmeticException();
//add a cause
ae.initCause(new IOException("Original cause"));
throw ae;
}
public static void main(String args[])
{
try
{
compute();
}
catch(Exception e)
{
System.out.println("Caught:"+ e);
//display cause exception
System.out.println("Original clause:"+ e.getCause());
}
}
}

Output:
Caught:java.lang.ArithmeticException
Original clause:java.io.IOException: Original cause

Three recently added Exception features


Following are the three new features added to Exceptions.
1. try-with-resources statement
2. multi-catch statement
3.precise rethrow statement

1. try-with-resources
In Java, resources can be closed automatically by using try-with-resources statement
feature. This process is called as Automatic Resource management (ARM).
Syntax:
try(resource-specification)
{
}

JAVA UNIT - III Page 42

You might also like