0% found this document useful (0 votes)
62 views43 pages

L24 Exception Handling

The document discusses exception handling in Java. It defines exceptions as abnormal runtime errors and describes how exceptions are represented as objects in Java. It covers the exception hierarchy with Throwable at the root and Exception and Error as subclasses. It also discusses checked and unchecked exceptions, commonly used exception classes, and keywords like try, catch, throw, throws, and finally that are used for exception handling in Java.

Uploaded by

adarsh raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views43 pages

L24 Exception Handling

The document discusses exception handling in Java. It defines exceptions as abnormal runtime errors and describes how exceptions are represented as objects in Java. It covers the exception hierarchy with Throwable at the root and Exception and Error as subclasses. It also discusses checked and unchecked exceptions, commonly used exception classes, and keywords like try, catch, throw, throws, and finally that are used for exception handling in Java.

Uploaded by

adarsh raj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Programming in Java

Exception Handling

By
Arvind Kumar
Asst. Professor, LPU
Introduction
• An exception is an abnormal condition that arises in a code
sequence at run time.

• In other words, an exception is a run-time error.

• A Java exception is an object that describes an exceptional (that


is, error) condition that has occurred in a piece of code.
Exception Handling
class Exception
{
public static void main (String arr[])
{
System.out.println(“Enter two numbers”);
Scanner s = new Scanner (System.in);
int x = s.nextInt();
int y = s.nextInt();
int z = x/y;
System.out.println(“result of division is : ” + z); }
}
Exception Handling

• An Exception is a run-time error that can be handled


programmatically in the application and does not result in
abnormal program termination.

• Exception handling is a mechanism that facilitates


programmatic handling of run-time errors.

• In java, each run-time error is represented by an object.


Exception (Class Hierarchy)
• At the root of the class hierarchy, there is an class named ‘Throwable’ which
represents the basic features of run-time errors.

• There are two sub-classes of Throwable.


• Exception : can be handled
• Error : can’t be handled

• RuntimeException is the sub-class of Exception.

• Exceptions of this type are automatically defined for the programs that we
write and include things such as division by zero and invalid array indexing.

• Each exception is a run-time error but all run-time errors are not exceptions.
Throwable

Exception Error

Run-time Exception - StackOverFlow


• IOException - ArithmeticException - NoSuchMethod
• SQLException - ArrayIndexOutOf
BoundsException
- NullPointerException
Checked Exception
Unchecked Exception
Checked Exception
• Checked Exceptions are those, that have to be either caught or
declared to be thrown in the method in which they are raised.

Unchecked Exception
• Unchecked Exceptions are those that are not forced by the
compiler either to be caught or to be thrown.

• Unchecked Exceptions either represent common programming


errors or those run-time errors that can’t be handled through
exception handling.
Commonly used sub-classes of Exception
• ArithmeticException

• ArrayIndexOutOfBoundsException

• NumberFormatException

• IOException
Commonly used sub-classes of Errors
• StackOverFlowError

• NoClassDefFoundError

• NoSuchMethodError
Uncaught Exceptions
class Exc0
{
public static void main(String args[])
{
int d = 0;
int a = 42 / d;
}
}

• When the Java run-time system detects the attempt to divide by zero,
it constructs a new exception object and then throws this exception.
• once an exception has been thrown, it must be caught by an
exception handler and dealt with immediately.
• In the previous example, we haven’t supplied any exception handlers
of our own.

• So the exception is caught by the default handler provided by the


Java run-time system.

• Any exception that is not caught by your program will ultimately be


processed by the default handler.

• The default handler displays a string describing the exception, prints


a stack trace from the point at which the exception occurred, and
terminates the program.

java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:6)


Keywords for Exception Handling
• try

• catch

• throw

• throws

• finally
Why Exception Handling?
• When the default exception handler is provided by the Java
run-time system , why Exception Handling?

• Exception Handling is needed because:


– it allows to fix the error, customize the message
– it prevents the program from automatically terminating
Keywords for Exception Handling
try:
• used to execute the statements whose execution may result in
an exception.

try {
Statements whose execution may cause an exception
}

Note: try block is always used either with catch or finally or with
both.
Keywords for Exception Handling
catch:
• catch is used to define a handler.

• It contains statements that are to be executed when the


exception represented by the catch block is generated.

• If program executes normally, then the statements of catch


block will not executed.

• If no catch block is found in program, exception is caught by


JVM and program is terminated.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}}
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{ d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}}
Division by zero.
After catch statement.
Multiple catch Clauses
• In some cases, more than one exception could be raised by a
single piece of code.

• To handle this type of situation, you can specify two or more


catch clauses, each catching a different type of exception.

• When an exception is thrown, each catch statement is


inspected in order, and the first one whose type matches that
of the exception is executed.

• After one catch statement executes, the others are bypassed,


and execution continues after the try/catch block
class Divide{
public static void main(String arr[]){
try {
int a= Integer.parseInt(arr[0]);
int b= Integer.parseInt(arr[1]);
int c = a/b;
System.out.println(“Result is: ”+c);
}
catch (ArithmeticException e)
{System.out.println(“Second number must be non-zero”);}

catch (NumberFormatException n)
{System.out.println(“Arguments must be Numeric”);}

catch (ArrayIndexOutOfBoundsException a)
{System.out.println(“Invalid Number of arguments”);}
}
}
Nested try Statements
• 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 statement’s 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 run-time system


will handle the exception.
class NestTry
{public static void main(String args[])
{try
{int a = args.length;
int b = 42 / a;
System.out.println("a = " + a);
try
{if(a==1) a = a/(a-a);
if(a==2) {int c[] = { 1 };
c[42] = 99;}
}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("Array index out-of-bounds: " + e);}
}
catch(ArithmeticException e)
{System.out.println("Divide by 0: " + e);}
} }
Defining Generalized Exception Handler

• A generalized exception handler is one that can handle the


exceptions of all types.

• If a class has a generalized as well as specific exception


handler, then the generalized exception handler must be the
last one.
class Divide{
public static void main(String arr[]){
try {
int a= Integer.parseInt(arr[0]);
int b= Integer.parseInt(arr[1]);
int c = a/b;
System.out.println(“Result is: ”+c);
}
catch (Throwable e)
{
System.out.println(e);
}
}
}
Keywords for Exception Handling
throw:
• used for explicit exception throwing.
throw(Exception obj);

‘throw’ keyword can be used:


• to throw user defined exception
• to customize the message to be displayed by predefined exceptions
• to re-throw a caught exception

• Note: System-generated exceptions are automatically thrown by


the Java run-time system.
class ThrowDemo
{
static void demoproc()
{
try {throw new NullPointerException("demo");}
catch(NullPointerException e)
{System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[])
{
try {
demoproc();
}
catch(NullPointerException e)
{System.out.println("Recaught: " + e);}
}
}
Keywords for Exception Handling
throws
• A throws clause lists the types of exceptions that a method might
throw.
type method-name(parameter-list) throws exception-list
{
// body of method
}
• This is necessary for all exceptions, except those of type Error or
Runtime Exception, or any of their subclasses.

• All other exceptions that a method can throw must be declared in


the throws clause. If they are not, a compile-time error will result.
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);}
}
}
Keywords for Exception Handling

Finally
• 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.

• The finally block will execute whether or not an exception is


thrown.

• If an exception is thrown, the finally block will execute even


if no catch statement matches the exception.
• If a finally block is associated with a try, the finally block will
be executed upon conclusion of the try.

• The finally clause is optional. However, each try statement


requires at least one catch or a finally clause.
class FinallyDemo
{static void procA()
{ try{ System.out.println("A try");
throw new RuntimeException();
}
finally { System.out.println("A finally"); }
}
static void procB()
{
try {System.out.println("B try"); return; }
finally { System.out.println("B finally"); }
}
public static void main(String args[])
{ try { procA();}
catch (Exception e) { System.out.println("Exception caught"); }
procB();
}
}
Let’s Do It
• Write a program in Java to display the names and roll numbers
of students. Initialize respective array variables for 10
students. Handle ArrayIndexOutOfBoundsExeption, so that
any such problem doesn’t cause illegal termination of
program.
• WAP in which prompt the user to enter a number x which is
not divisible by a number y entered by user. If x is divisible by
y then create an exception and throw it. Also ask user to re-
enter the number and repeat the process.
Defining Custom Exceptions
• We can create our own Exception sub-classes by inheriting
Exception class.

• The Exception class does not define any methods of its own.

• It inherits those methods provided by Throwable.

• Thus, all exceptions, including those that we create, have the


methods defined by Throwable available to them.
Constructor for creating Exception

• Exception( )
• Exception(String msg)

• A custom exception class is represented by a subclass of


Exception.

• It contains the above mentioned constructor to initialize


custom exception object and a toString() that returns a
message represented by custom exception object.
class MyException extends Exception
{ private int detail;
MyException(int a) {detail = a;}
public String toString() {return "MyException[" + detail + "]“;}
}
class ExceptionDemo
{static void compute(int a) throws MyException
{
System.out.println("Called compute(" + a + ")");
if(a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[])
{try {compute(1); compute(20); }
catch (MyException e) {System.out.println("Caught " + e);}
}
}
Let’s Do It
• can we use throws in catch signature
• can we define more than 1 finally block for single try block
• can we define try block within catch
• can we define try block without catch
• can we handle the exception by using Throwable
• can we handle the Error also.
• can we define try within finally
• can we create the object of RuntimeException class
• can we throw the object of Throwable class using throw
keyword
• can we throw objects of Error using throw keyword
• Write a code to generate two exception at the same time
Let’s Do It
• WAP in which prompt the user to enter a number. If the
number is less than 10 the throw an exception and display
"Number is less than 10" and if it is greater than 20 then throw
an exception and display "Number is greater than 20" rethrow
the exception in both the cases to print Thanks for using this
test.
• Create a class Student with attributes roll no, age and
course_no. Initialize values through parameterized constructor.
If age of student is not between 15 and 21 then generate user-
defined exception “AgeNotWithinRangeException”.
• WAP to save and display name, emp_id, and address of
employee. Your program should throw and handle number
format exception if emp_id does not contain at least one digit.
Let’s Do It
• WAP to enter and check the string contains JAVA. If it not
contains JAVA then throw NumberFormatException and
handle it.
Assertions
• An assertion is a statement in the Java programming language
that enables you to test your assumptions about your program. 

• Each assertion contains a boolean expression that you believe


will be true when the assertion executes. If it is not true, the
system will throw an error. 

• Writing assertions while programming is one of the quickest


and most effective ways to detect and correct bugs.
Assertions
• The assertion statement has two forms.
assert Expression1 ;
• where Expression1 is a boolean expression. When the system
runs the assertion, it evaluates Expression1 and if it
is false throws an AssertionError with no detail message.

assert Expression1 : Expression2 ;


• Expression1 is a boolean expression.
• Expression2 is an expression that has a value. (It cannot be an
invocation of a method that is declared void.)
Enabling and Disabling Assertions
• By default, assertions are disabled at runtime. 
• To enable assertions use the -enableassertions, or -ea.
• To disable assertions use the -disableassertions, or -da.
Assertions
// Demonstrate assert.
class AssertDemo
{
static int val = 3;
static int getnum()
{
return val--;
}
public static void main(String args[])
{
int n;
for(int i=0; i < 10; i++)
{
n = getnum();
assert n > 0; // will fail when n is 0
System.out.println("n is " + n);
}
}
}
Assertions
// Demonstrate assert Second Form.
class AssertDemo
{
static int val = 3;
static int getnum()
{
return val--;
}
public static void main(String args[])
{
int n;
for(int i=0; i < 10; i++)
{
n = getnum();
assert n > 0 : "n is negative!"; // will fail when n is 0 with message
System.out.println("n is " + n);
}
}
}

You might also like