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

Lecture 12 Exception Handling With Assertion

oop

Uploaded by

aliza
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)
14 views

Lecture 12 Exception Handling With Assertion

oop

Uploaded by

aliza
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/ 73

Lecture#11

Exception Handling

Course: Object oriented Programming (CE-205)


Course Teacher: Dr Umm-e-Laila& Ms.Aneeta Siddiqui

Contact Info:
Room No: BS-04, CED
1 Email: [email protected]
Course Books

 Text Book:
 Herbert Schildt, Java: The Complete Reference, 12th
Edition ,McGraw-Hill Education.
 Deitel, Paul, Java How to Program, 11th Edition, Pearson,
2017

 Reference Books:
 Horton, Ivor, Beginning Java, 7th Edition, Wrox, 2011

2
Course Instructors

 Dr. Umm-e-Laila [email protected]


Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536

 Aneeta Siddiqui [email protected]


Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Marks Distribution

Assignments + Quiz ______________

20

Mid Term ______________

30

Semester Final Paper ______________


4
50
5 Introduction
 Rarely does a program runs
successfully at its very first
attempt.
 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.
Common Runtime Errors
6
 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
 Any more ….
Runtime Errors
7

1 import java.util.Scanner;
2
3 public class ExceptionDemo {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6 System.out.print("Enter an integer: ");
7 int number = scanner.nextInt();
8 If an exception occurs on this
9 line, the rest of the lines in the // Display the result
method are skipped and the System.out.println(
10
program is terminated.
11 "The number entered is " + number);
12 }
13 }
Terminated.
Exception Classes
8

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


System Errors
9

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

System errors are LinkageError Several more classes


thrown by JVM and
represented in the Error VirtualMachineError
class. The Error classError
describes internal AWTError
system errors. Such
errors rarely occur. If Several more classes
one does, there is little
you can do beyond
notifying the user and
trying to terminate the
Exceptions
10

Exception ClassNotFoundException
describes errors
caused by your IOException
program and ArithmeticException
external Exception AWTException
circumstances. NullPointerException
These errors can RuntimeException
be caught and IndexOutOfBoundsException

handled
Object by your
Throwable Several more classes
IllegalArgumentException
program.
LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


Runtime Exceptions
11

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
RuntimeException is
Error
caused by programming
AWTError errors, such as bad
casting, accessing an
Several more classes out-of-bounds array, and
numeric errors.
12 Without Error Handling –
Example 1
class NoErrorHandling{
public static void main(String[] args){
int a,b;
a = 7;
b = 0;
Program does not reach here
System.out.println(“Result is “ + a/b);
System.out.println(“Program reached this line”);
}
}
No compilation errors. While running it reports an error and stops w
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java
Traditional way of Error
13
Handling - Example 2
class WithErrorHandling{
public static void main(String[] args){
int a,b;
a = 7; b = 0;
if (b != 0){
System.out.println(“Result is “ + a/b);
}
else{
Program reaches here
System.out.println(“ B is zero);
}
System.out.println(“Program is complete”);
}
}
14 Error Handling
 Any program can find itself in unusual circumstances – Error
Conditions.

 A “good” program should be able to handle these conditions


gracefully.

 Java provides a mechanism to handle these error condition -


exceptions
Exceptions
15
 Exception is a run-time error which arises
during the execution of java program. The
term exception in java stands for an
exceptional event. It can be defined as
abnormal event that arises during the
execution and normal flow of program.
 An exception is a condition that is caused by
a runtime error in the program.
 Provide a mechanism to signal errors directly
without using flags.
 Allow errors to be handled in one central part
of the code without cluttering code.
16 Exceptions and their Handling

 When the JVM encounters an error


such as divide by zero, it creates
an exception object and throws it
– as a notification that an error
has occurred.
 If the exception object is not
caught and handled properly, the
interpreter will display an error
and terminate the program.
17 Exceptions and their Handling

 If we want the program to


continue with execution of the
remaining code, then we should
try to catch the exception object
thrown by the error condition and
then take appropriate corrective
actions. This task is known as
exception handling.
18 Common Java Exceptions
 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
Exception hierarchy
 Java organizes exceptions in inheritance tree:
 Throwable
 Error
 Exception
 RuntimeException
 TooManyListenersException
 IOException
 AWTException
 All Exceptions are inherited from Runtime Exception.
 An Exception is a class.
 String is a property of throwable class and whenever exception
occur JRE passes a message.
 String in throwable is private and get message is public.
Exceptions in Java
 20
A method can signal an error condition by
throwing an exception – throws
 The calling method can transfer control to a
exception handler by catching an exception
- try, catch
 Clean up can be done by - finally
 Try and Catch ,Finally are bound to each
other. Try must be with Catch or Finally.
 Sequence is Try,Catch,Finally. Nothing can
be written b/w Try and Catch blocks.
 JVM always catch Exception(by default).
21 Exception Handling Mechanism

try Block

Statements that causes


an exception

Throws
exception
catch Block
Object
Statements that
handle the exception
22
Syntax of Exception
Handling Code


try {
// statements
}
catch( Exception-Type e)
{
// statements to process exception
}
..
..
With Exception Handling
23
- Example 3
class WithExceptionHandling{
public static void main(String[] args){
int a,b; float r;
a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
Program Reaches here
}
catch(ArithmeticException e){
System.out.println(“ B is zero);
}
System.out.println(“Program reached this line”);
}
}
Finding a Sum of Integer
Values Passed as
24

Command Line Parameters


// ComLineSum.java: adding command line
parameters
class ComLineSum
{
public static void main(String args[])
{
int InvalidCount = 0;
int number, sum = 0;

for( int i = 0; i < args.length; i++)


{
try {
number =
Integer.parseInt(args[i]);
}
Finding a Sum of Integer
Values Passed as
25

Command Line Parameters


catch(NumberFormatException e)
{
InvalidCount++;
System.out.println("Invalid Number:
"+args[i]);
continue;//skip the remaining part of
loop
}
sum += number;
}
System.out.println("Number of Invalid Arguments
= "+InvalidCount);
System.out.println("Number of Valid Arguments =
"+(args.length-InvalidCount));
System.out.println("Sum of Valid Arguments =
"+sum);
}
}
With Exception Handling -
26
Example 3 output
java ComLineSum 1 2
Number of Invalid Arguments =
0
Number of Valid Arguments = 2
Sum of Valid Arguments = 3

java ComLineSum 1 2 abc


Invalid Number: abc
Number of Invalid Arguments =
1
Number of Valid Arguments = 2
Sum of Valid Arguments = 3
With Exception Handling
27 - Example 4
Class ExampleException{
public static void main(String args[]){
division(2,0);
System.out.print(“return from main”);
}
static void division(int i,int j)The type of
try{ exception raised
contain same
System.out.print(“i/j”+i/j);} type of object
catch(Arithmetic Exception e) throw i.e
Arithmetic
{System.out.print(“catch”); Exception
}
System.out.print(“return from division”); }
28 With Exception Handling -
Example 4 output
If i=2 and j=4
return from division
return from main
If i=10 and j=0
o/p is catch Exception get at
return from division
System.out.print(i/j);
return from main
Multiple Catch Statements
 A try block can be followed by one or more
catch blocks. Each catch block must
contain a different exception handler. So, if
you have to perform different tasks at the
occurrence of different exceptions, use
java multi-catch block.
 At a time only one exception occurs and at
a time only one catch block is executed.
 All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before
catch for Exception.
Multiple Catch Statements
30

 If a try block is likely to raise more than


one type of exceptions, then multiple
catch blocks can be defined as follows:
……
try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
....
catch( Exception-TypeN e)
{
// statements to process exception N
}

With Exception Handling
31
-Class
Example 5
ExampleException{
public static void main(String args[]){
division(2,0);
System.out.print(“return from main”); }
static void division(int i,int j){
int iArray={1,2,3};
try{ System.out.print(“i/j”+(i/j));
for(int i=0;i<=3;i++) The type of
exception raised
{ System.out.print(iArray[i]);
contain same
} } type of object
catch(ArithmeticException e) throw i.e
Arithmetic
{System.out.print(“catch”);}
Exception
catch(ArrayIndexOutOfBoundException e)
{System.out.print(“Index
finally block
32

 Java supports definition of another block called finally that


be used to handle any exception that is not caught by any
of the previous statements. It may be added immediately
after the try block or after the last catch block:

try {
// statements
}
catch( Exception-Type1 e)
{
// statements to process exception 1
}
finally {
….
}
finally block
33

 When a finally is defined, it is executed regardless of


whether or not an exception is thrown. Therefore, it is also
used to perform certain house keeping operations such as
closing files and releasing system resources.
 If exception is raised in try and catched the abrupt
termination then the code after finally execute.
 If exception is raised in try but not catched than the finally
is execute but code after finally does not execute .
With Exception Handling
34 - Example 6
Class ExampleException{
public static void main(String args[]){
try{
division(2,0);}
finally{
System.out.print(“finally”);
}
System.out.print(“return from main”);
}
static void division(int i,int j){
System.out.print(“i/j”+i/j);}
System.out.print(“return from division”); }
With Exception Handling -
35 Example 6 output
 Division(2,0)
finally
Exception in thread "main"
java.lang.ArithmeticException: / by
zero at
exception.Example6.division(Exampl
e6.java:23) at
exception.Example6.main(Example6.j
ava:16)

 Division(2,2)
i/j 1
return from division
finally
Return from main
36
Catching and
Propagating Exceptions
 Exceptions raised in try block can be caught
and then they can be thrown again/propagated
after performing some operations. This can be
done by using the keyword “throw” as follows:
 throw exception-object;
 OR
 throw new Throwable_Subclass;
Catching and Propagating
37
Exceptions
 If an exception is raise in try but not catch than it goes to
finally but if finally also throw some other exception then
the rest of code is not execute and the last abrupt exception
is throw by default handler.
catch (ArthematicException e){
s.o.p(“except caught”);
}
throw e;
}
 //goes to default handler as we run in sequence.
 Exception that are from run time Exception; and error are
uncaught exception.
 All other from exception class are caughtable.
With Exception Handling
38
- Example 7
class WithExceptionCatchThrow{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program Does Not
reach here
catch(ArithmeticException e){
when exception occurs System.out.println(“ B is zero);
throw e;
}
System.out.println(“Program is complete”);
}
}
With Exception Handling
- Example 8
39

class WithExceptionCatchThrowFinally{
public static void main(String[] args){
int a,b; float r; a = 7; b = 0;
try{
r = a/b;
System.out.println(“Result is “ + r);
}
Program catch(ArithmeticException e){
reaches here System.out.println(“ B is zero);
throw e;
}
finally{
System.out.println(“Program is complete”);
}
}
}
Using printStackTrace and
getMessage
 Class Throwable
 Superclass of all exceptions
 Offers method printStackTrace
 Prints method call stack for caught
Exception object
 Most recent method on top of stack
 Helpful for testing/debugging
 Constructors
 Exception()
 Exception( String informationString )
 informationString may be accessed
with method getMessage
With Exception Handling
41 - Example 9 Call method1, which calls
class WithExceptionCatchThrows{ method2, which calls method3,
which throws an exception.
public static void main(String[] args){
try{
method1();
} getMessage prints the
catch(Exception e){ String the Exception was
System.err.println( e.getMessage() + "\n" ); initialized with.
e.printStackTrace();
printStackTrace prints the
} methods in this order:
} method3
public static void method1() throws Exception{ method2
method2(); method1
main
} (order they were called when
public static void method2() throws Exception{ exception occurred)
method3();}
public static void method3() throws Exception{
throw new Exception( "Exception thrown in method3" );
}}
42 With Exception Handling -
Example 9 output

Exception thrown in method3


java.lang.Exception: Exception thrown in method3
at
UsingExceptions.method3(UsingExceptions.java:28)
at
UsingExceptions.method2(UsingExceptions.java:23)
at
UsingExceptions.method1(UsingExceptions.java:18)
at
UsingExceptions.main(UsingExceptions.java:8)
Execution of try catch blocks
 For normal execution:
 try block executes,
 then finally block executes,
 then other statements execute

 When an error is caught and the catch block throws


an exception or returns:
 try block is interrupted
 catch block executes (until throw or return
statement)
 finally block executes
Execution of try catch blocks
 When error is caught and catch block doesn’t throw
an exception or return:
 try block is interrupted
 catch block executes
 finally block executes
 other statements execute

 When an error occurs that is not caught:


 try block is interrupted
 finally block executes
10-
45
Checked Exceptions
 An exception is either checked or
unchecked
 A checked exception either must be caught
by a method, or must be listed in the
throws clause of any method that may
throw or propagate it
 A throws clause is appended to the method
header
 The compiler will issue an error if a
checked exception is not caught or
asserted in a throws clause
Unchecked Exceptions
10-
46  An unchecked exception does not require
explicit handling, though it could be
processed that way
 The only unchecked exceptions in Java are
objects of type RuntimeException or any
of its descendants
 Errors are similar to RuntimeException
and its descendants in that:
 Errors should not be caught
 Errors do not require a throws clause
Creating Custom Exception
47
Classes
 Use the exception classes in the API whenever
possible.
 Create custom exception classes if the
predefined classes are not sufficient.
 Declare custom exception classes by extending
Exception or a subclass of Exception.
48 User-Defined Exceptions

 Problem Statement :
 Consider the example of the Circle
class
 Circle class had the following
constructor
public Circle(double centreX, double centreY,
double radius){
x = centreX; y = centreY; r = radius;
}

 How would we ensure that the radius


is not zero or negative?
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
User-Defined Exceptions
50
in standard format
class MyException extends Exception
{
MyException(String message)
{
super(message); // pass to superclass if parameter is not handled
by used defined exception
}
}
class TestMyException {
… Get Message is a method defined in a stan
try {
..
Exception class .
throw new MyException(“This is error message”);
}
catch(MyException e)
{
System.out.println(“Message is: “+e.getMessage());
}
}
}
Example1:Defining your own
51
exceptions
import java.lang.Exception;
class InvalidRadiusException extends Exception {

private double r;

public InvalidRadiusException(double radius){


r = radius;
}
public void printError(){
System.out.println("Radius [" + r + "] is not valid");
}
}
52
Throwing the exception
class Circle {
double x, y, r;

public Circle (double centreX, double


centreY, double radius ) throws
InvalidRadiusException {
if (r <= 0 ) {
throw new
InvalidRadiusException(radius);
}
else {
x = centreX ; y = centreY; r =
radius;
} }}
53
Catching the exception

class CircleTest {
public static void main(String[] args){
try{
Circle c1 = new Circle(10, 10, -1);
System.out.println("Circle created");
}
catch(InvalidRadiusException e)
{
e.printError();
}
}
}
Example 2: Defining your
54

own exceptions
public class DivException extends Exception {
DivException()
{super(“Div error Exception…");} Exception have two constructors
String argument
Zero argument
DivException(String str)
{super(str);}
User will throw this exception if divisor is 0

@override
public String getMessage(){
return super.getMessage();
}
}
Example 2: Defining
55

your own exceptions


public class MyException extends Exception {
MyException()
{super("a<b in my Exception…");}

MyException(String str)
User will throw this exception if dividend <divisor
{super(str);} A=5
B=10
A<B

@Override
public String getMessage(){
return super.getMessage();
}
}
Throwing & Catching the
56 exception
public class testMyException { finally{
public static void main(String[] System.out.println("Close
args){
File");
int a=10,b=20;
System.out.println("pakistan");
try{
}
if(a<b) throw new MyException(); System.out.println("hello
divide(a,b);
Karachi");
} }
catch(MyException e ){ static void divide(int i,int j) throws
System.out.println("MyException DivException{
Comes"); if(j==0) throw new
System.out.println(""+e.toString()); DivException();
} catch(DivException e ){
System.out.println(""+i/j);
System.out.println("DivException
Comes");
System.out.println(""+e.toString());
}
}
}
Example 2: output
57

If a=10 b=20
pakistan
MyException COmes
exception.MyException: a<b in my Exception…
Close File
hello Karachi

If a=20 b=0
pakistan
DivException COmes
exception.DivException
Close File
hello Karachi
Exceptions are ubiquitous in Java

 Exception handling required for all read


methods
 Also many other system methods
 If you use one of Java's built in class
methods and it throws an exception, you
must catch it (i.e., surround it in a try/catch
block) or rethrow it, or you will get a
compile time error:
char ch;
try { ch = (char) System.in.read(); }
catch (IOException e)
{ System.err.println(e); return;
Assertions
59

 An assertion is a Java statement that


enables you to assert an assumption
about your program. An assertion
contains a Boolean expression that
should be true during program
execution. Assertions can be used to
assure program correctness and avoid
logic errors.
 It provides an effective way to detect
and correct programming errors.
Assertions Syntax
60

 There are two ways to use assertion. First way is:


assert expression;
 and second way is:
assert expression1 : expression2;
Executing Assertions
61

When an assertion statement is executed,


Java evaluates the assertion.

If it is false, an AssertionError will be thrown.

The AssertionError class has a no-arg


constructor and seven overloaded single-
argument constructors of type int, long, float,
double, boolean, char, and Object.
Executing Assertions
62

For the first assert statement with no detail


message, the no-arg constructor of
AssertionError is used.

 For the second assert statement with a


detail message, an appropriate
AssertionError constructor is used to match
the data type of the message.

Since AssertionError is a subclass of Error,


when an assertion becomes false, the
program displays a message on the console
and exits.
Assertions Example 1
63

 Use assertions to do occasionally check:


import java.util.Scanner;

class AssertionExample{
public static void main( String args[] ){

Scanner scanner = new Scanner( System.in );


System.out.print("Enter ur age ");

int value = scanner.nextInt();


assert value>=18:" Not valid";

System.out.println("value is "+value);
}
}
Run Assertion
64

 Assertion is disabled by default. To enable the


assertion, -ea or -enableassertions switch of java
must be used.
1. Compile it by: javac AssertionExample.java

 In Netbeans For regular Apps and Swing Apps:


1. Right click on the project in the Project Explorer
2. Choose Properties (at the bottom of pop up menu)
3. Choose Run (under Categories)
4. Set the VM Options field to include –enableassertions or
-ea
5. Click [OK]
65 Assertion Example Output
Enter ur age 11
Exception in thread "main" java.lang.AssertionError:
Not valid
at exception.Asser.main(Asser.java:22)
C:\Users\Hp\AppData\Local\NetBeans\Cache\8.2\
executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 3 seconds)
Assertions Example 2
66

public class AssertionDemo {


public static void main(String[] args) {
int i; int sum = 0;
for (i = 0; i < 10; i++) {
sum += i;
}
assert i == 10;
assert sum > 10 && sum < 5 * 10 : "sum is " + sum;
}
}
How to Remove Assertions Code?
67

 Use a static final variable that is set to true


during debugging and to false when the
program is deployed:
public void f(int[] a, int i)
{
if (debug)
Assertion.check (a != null &&
i >= 0 && i < a.length);

}
 Better solution: put the test into a separate
class and not ship the code for that class with
the release version – anonymous class:
public void f(final int[] a, final int i)
68 {// debug is not necessarily to be static final
if (debug)
new Assertion()
{ {check (a != null && i >= 0 &&
i < a.length);}
}}
 new Assertion() { … } create an object of an anonymous
class that inherits from Assertion. This class has no
method, just a constructor. The constructor is written as
an initialization block.
 new Assertion(){{check (…);}}; When debug value is true
then the compiler loads the inner class and constructs an
assertion object. The constructor calls the static check
method of the Assertion class and tests the condition. If
debug is false, the inner class is not even loaded – the
inner class code need not to be shipped with the release
version of program.
Using Exception Handling or Assertions
69

 Assertion should not be used to replace exception


handling.
 Exception handling deals with unusual
circumstances during program execution.
Assertions are to assure the correctness of the
program.
 Exception handling addresses robustness and
assertion addresses correctness.
 Like exception handling, assertions are not used for
normal tests, but for internal consistency and
validity checks.
 Assertions are checked at runtime and can be
turned on or off at startup time.
Using Exception Handling or Assertions,
cont.
70

 Do not use assertions for argument


checking in public methods.
 Valid arguments that may be passed to a
public method are considered to be part of
the method’s contract. The contract must
always be obeyed whether assertions are
enabled or disabled. For example, the
following code should be rewritten using
exception handling .
public void setRadius(double newRadius) {
assert newRadius >= 0;
radius = newRadius;
}
Using Exception Handling or Assertions,
cont.
71

 Use assertions to reaffirm assumptions.


This gives you more confidence to assure
correctness of the program. A common use
of assertions is to replace assumptions with
assertions in the code.
Using Exception Handling or Assertions, cont.
72

Another good use of assertions is place


assertions in a switch statement without a
default case. For example,
switch (month) {
case 1: ... ; break;
case 2: ... ; break;
...
case 12: ... ; break;
default: assert false : "Invalid month: " + month
}
Summary
73
 Try block, code that could have
exceptions / errors
 Catch block(s), specify code to
handle various types of
exceptions. First block to have
appropriate type of exception is
invoked.
 If no ‘local’ catch found, exception
propagates up the method call
stack, all the way to main()
 Any execution of try, normal
completion, or catch then
transfers control on to finally

You might also like