Sei sulla pagina 1di 72

Exception Handling and

Assertions

1
Java
Contents

1 What is an exception ?
2 What is exception handling?
3 Exception hierarchy
4 Exception classification
5 Syntax
6 catch statement
7 Handling exceptions in the code
8 Multiple catches
9 Sequencing catches
10 Nesting try blocks

2
Java
Contents

11 Exception class
12 throw
13 Throws
14 Rethrow
15 Finally
16 Possible Solutions
17 Java’s solution –finally
18 Few points on syntax
19 Stack Trace
20 User-defined exceptions

3
Java
Contents

22 Common unchecked exception classes


23 NullPointerException
24 ClassCastException
25 ExceptionInInitializerError
26 StackOverflowError
27 NoClassDefFoundError
28 Assertions
29 Assert
30 Assertion enabling

4
Java
contents

31 Assertion disabling

32 When (not) to use assertions

33 Overriding and Exception

5
Java
Know
• What an exception is
• The Exception hierarchy and different types of
exceptions
• The Exception class methods
• The difference between throws, throw and rethrow

6
Java
Know
• The common exception classes
• Assertions

7
Java
Be Able To
• Implement exception handling effectively in Java
programs
• Create user- defined exceptions
• Use assertions

8
Java
What is an exception ?

class DivideByZero{
public static void main(String
str[])
{
int z= 45/0;
}}
Runtime error
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at DivideByZero.main(DivideByZero.java:5)
Folder 1
9
Java
An exception is an abnormal condition that arises
while running a program.

Examples:
•Attempt to divide an integer by zero causes an
exception to be thrown at run time.
•Attempt to call a method using a reference that is
null.
•Attempting to open a nonexistent a file for reading.
•JVM running out of memory.

10
Java
What is exception handling?

Exception handling consists of anticipating the


possibilities of abnormal conditions occurring during
program execution and taking care of this in the code

11
Java
Why exception handling?
Handling exceptions is required
•To give users friendly, relevant messages when
something goes wrong.
•To conduct certain critical tasks such as “save work”
or “close open files/sockets” in case some occurrence
forces abnormal termination.
•To allow programs to terminate gracefully or operate
in degraded mode.

12
Java
Exception Hierarchy

java.lang.Throwable

java.lang.Exception java.lang.Error

java.lang. VirtualMachineError
checked unchecked

13
Java
Exception classification
1) Checked exception or compiler-enforced
exceptions
2) Unchecked exceptions or runtime exception

hierarchy…

14
Java
java.lang.Exception java.lang.Error
unchecked exception

unchecked exception
java.lang.RuntimeException java.io.IOException

java.sql.SQLException
java.lang.ArithmeticException checked exception

java.lang.NullPointerException many more classes …

many more classes…


15
Java
unchecked exception
Attempt to divide by zero causes an exception to
be thrown at run time.(ArithmeticException)
Attempt to call a method using a reference that is
null.(NullPointerException) RuntimeException

Attempting to open a nonexistent file for


reading.(FileNotFoundException) checked exception

unchecked exception
JVM running out of memory. Error

16
Java
Syntax
Exception handling block:
try{ Code that may throw exception
… One of these is compulsory
}
catch(ExceptionType1 e){ …}
[catch(ExceptionType2 e){ …}]
finally { ... }

17
Java
catch statement
• The try block may throw one or more kinds of
exception object. Each catch block is written to
handle the exception of a certain kind.
try{
exception of type ExceptionType1 is thrown.
//Line 1: Line 3 not executed. Code jumps to
//Line 2:
//Line 3
}
catch(ExceptionType1 e){ …}
catch(ExceptionType2 e){ …}
Example…
//Line 4:
18
Java
Handling exceptions in the
code
public class NullException {
static String s;
public static void main(String[] a){
try{
System.out.println(s.length()); }
catch(NullPointerException n){
System.out.println("String not
initialized");
This code handles unchecked exception.
}}} Folder 2
19
Java
Multiple catches
public class NoArgument{
public static void main(String[] args){
try{
int j=10/args.length;
System.out.println(j);
System.out.println(args[1]);
}catch(ArithmeticException e){ First catch
System.out.println("command line
arguments not entered"); }
Folder 3 20
Java
catch(ArrayIndexOutOfBoundsException
a){ Second catch
System.out.println("command line 2nd
arguments not entered");
}
}}

21
Java
Execution paths
Path 1: java NoArgument
command line arguments not entered
Path 2: java NoArgument 1
Result:
10
command line 2nd arguments not entered
Path 3: java NoArgument X Y exceptions
Result: 5
normal path
Y
22
Java
In execution path 1, why do you
think args.length is not throwing
NullPointerException ?

23
Java
Attempting to divide a floating point
number by 0 does not cause a
runtime exception.
double i=10/0.0;
System.out.println(i);
Having said that, execute and
checkout what the above code
prints.

24
Java
Sequencing catches
class DivideByZero {
public static void main(String[] args) {
try{ int i=10/0;}
Should
be moved catch(Exception e){
to correct System.out.println(“general error");}
compiler
catch(ArithmeticException e1){
error.
System.out.println(“div by zero ");}
}}
Why should I
waste my time for
something that is
never going to be
executed ?
compiler

25
Folder 4 Java
Nesting try blocks
public class MulTry {
public static void main(String[] s) {
try{ NegativeArraySizeException
handler in the outer try block
try{
String n[]= new String[s.length-1];
System.out.println(n[0]); }
catch(ArrayIndexOutOfBoundsException ae){
System.out.println("Out of bounds");}
26
Folder 5 Java
}
catch(NegativeArraySizeException ne){
System.out.println("Array size cannot
be negative");}
}}
Execution
Path 1: java MulTry
Prints: Array size cannot be negative
Path 2: java MulTry 1
Prints: Out of bounds 27
Java
All the exceptions we have seen
so far are unchecked
exceptions. Hence if we don’t
handle them explicitly ... you
know who will.

28
Java
Exception class
• Constructors:
public Exception()
public Exception(String message)
Important methods:
public String getMessage()
(inherited from Throwable)
public void printStackTrace()
(inherited from Throwable)
We will understand this after a while. Before that there are few
more keywords we need to learn.
29
Java
throw
• If a method needs to throw an Exception
explicitly, it can do so by using throw keyword.

• Throwing an unchecked exception:


public abstract class Person{
public void setName(String name){
if(name==null)
throw new
RuntimeException("Invalid name");
else this.name=name; }
…}
Folder 6
30
Java
class Test {
public static void main(String args[]){
new student.Student(“X”).setName(null);
}} On execution

Exception in thread "main" java.lang.RuntimeException:


Invalid name

We will see a bit later how to have our own exception class.

31
Java
• Throwing a checked exception:

public void setName(String name){


if(name==null)
throw new Exception("Invalid name");
else this.name=name; }

compilation

Unreported exception java.lang.Exception; must be caught or


declared to be thrown
32
Folder 7 Java
public void setName(String name){
try{
if(name==null)
throw new Exception("Invalid name");
else this.name=name; }}
catch(Exception e){
System.out.println(e.getMessage());
}

33
Folder 8 Java
I am bit confused… why do I need checked
exceptions! We achieved the same thing
without any ‘exception code’ !

public void setName(String name){


try{ if(name==null)
System.out.println(“Invalid Name”);
else this.name=name; }
}

34
Java
I am sure you are! Because the last
example does not exactly demonstrate
the use of checked exception. Usually
when a method throws a checked
exception, it does not handle it. Let us
say that when we set student’s name
to null, instead of printing “Invalid
name” we want to print “Invalid
student name”. But since the Person
class does not know if actual object is
going to be student or teacher or HOD
it would be best if it delegates the
printing to the calling method.

35
Java
throws
public void setName(String name)
throws Exception{
if(name==null)
throw new Exception("Invalid name");
else
this.name=name;
}
All the methods in Person class, Student class, Teacher class
that call setName() methods must handle this exception.
36
Folder 9 Java
class Test {
public static void main(String args[]){
try{
new student.Student(“X”).setName(null);
}catch(Exception e){
if(e.getMessage().equals(“Invalid
name”))
System.out.println(“Invalid student
name”);
The main method must handle the exception
}}} since it is calling the setName() method or ..
37
Java
public static void main() throws
Exception{
new student.Student(“X”).setName(“XX”);
}

In this case, calling method delegates the exception handling to the


JVM. It prints:

Exception in thread "main" java.lang.Exception: Invalid name

38
Java
rethrow
public class Rethrow {
public static void method(String s)
throws Exception{
if(s.equals("Hello"))
System.out.println(s);
else
try{
throw new Exception(“expecting hello");
39
Folder 10 Java
}catch(Exception ee){
System.out.println(“caught ”+ee);
throw ee; Method delegating
re-throw of exception object
}
public static void main(String s[]){
try{method(s[0]);
}catch(Exception e){
System.out.println(“Exception
Raised:”+e.getMessage());}}}

40
Java
finally
boolean read(){
try{
On exception
//open a file
//read from file
//close file
}
catch(IOException e){

} File not closed!


catch(Exception e1){
}}
41
Java
Possible Solutions
try{
//open a file Solution 1
//read from file
//close file
insert
}
catch(IOException e){ //close file

}
catch(Exception e1){
Repetition of code, not a
} good practice
42
Java
Solution 2
boolean read(){
try{
//open a file
//read from file
//close file Move
return true;
} If there is a return
catch(IOException e){ statement in try-catch
} block (or exception
handler) then we end up
catch(Exception e1){ with the same problem
} again!

return false;
43
Java
Java’s solution -finally
• Code enclose within a finally block will
always be executed (whether or not an exception
occurs).
• finally is a part of try-catch syntax
try{…}
catch(ExceptionType1 e){ …}
[catch(ExceptionType2 e){ …}]
finally { ... }

44
Java
boolean read(){
try{
//open a file
//read from file
return true;
}
catch(IOException e){}
catch(Exception e1){}
finally{
//close file Will always execute
}
return false;

45
Java
Example
class Canteen{
String name;
public static void main(String args[])
throws Exception{
if(args.length==1)
System.out.println(
luck(args[0].length()));
else
System.out.println(luck(args.length));
}
Folder 11 46
Java
public static String luck(int i){
String [] gifts={"a cup of coffee",
"a cup of tea","a Breakfast","a
Lunch", "a Dinner"};
try{
if(i>0 && i<6)
return "Congratulations!, you have
won "+gifts[i-1];
else throw new Exception(); }
catch(Exception e) {
return "Sorry ! Better luck next
time" }
47
Java
finally{
System.out.println("Thank you for
choosing to come to our canteen !
");
}
}}

48
Java
Few points on syntax
 A try block must have either a catch block or a finally
block.
 For an unchecked exception the code given below
compiles.
class Test{
public static void main(String s[]){
try{
throw new RuntimeException(); }
finally{ System.out.println("ok");
}} }
49
Java
 If a try block is throwing a checked exception then,
2) it must have a catch block. It may or may not have a
finally block.
3) OR the method must have a throws clause. In this case
finally block is required.

class Test{
public static void main(String
s[])throws Exception{
try{throw new Exception(); }
finally{System.out.println("ok"); }}
} 50
Java
Stack Trace
•If an exception is not caught in a method it is passed on and
on to the calling methods until some method handles it. If no
method handles it, the JVM handles it. The
printStackTrace() prints the trace of this exception
propagation.
•public class Stacktrace {
public static void main(String[] s) {
try{ y(); }catch(Exception e){
e.printStackTrace();}}
static void y(){ z();} Folder 12

static void z(){ int p=45/0;}} 51


Java
main(){ y(){ z(){
y(); z();

Exception passed on Exception raised
} }
printStackTrace();
}
Result of execution:

java.lang.ArithmeticException: / by zero
at Stacktrace.z(Stacktrace.java:17)
Stack
Trace at Stacktrace.y(Stacktrace.java:13)
at Stacktrace.main(Stacktrace.java:4)

52
Java
User-defined exceptions
package general;
public class InvalidNameException
extends Exception {
String exStr;
public InvalidNameException(){
exStr= "invalid name";
}
public InvalidNameException(String
s){exStr=s;}
Folder 13

53
Java
public String toString(){ return
"InvalidNameException" + exStr;}
}
public abstract class Person{
public void setName(String name) throws
InvalidNameException {
if(name==null)
throw new InvalidNameException();
else this.name=name; }}

}
54
Java
Common unchecked exception
classes We have seen this

• ArrayIndexOutOfBoundsException
• in Threads chapter
IllegalArgumentException
• in wrapper chapter
NumberFormatException
We will see a bit more of this
• NullPointerException
• ClassCastException
• IllegalStateException in IO
 ExceptionInInitializerError
 StackOverflowError
 NoClassDefFoundError We will see this when we do
 AssertionError assertions
55
Java
NullPointerException
• We already know that this inherits from
RunTimeException class.
• According to java documentation this exception is
thrown when an application attempts to use null in
cases where an object is required. These include:
3. Calling the instance method of a null object.
4. Accessing or modifying the field of a null object.
5. Taking the length of null as if it were an array.
6. Accessing or modifying the slots of null as if it
were an array.
7. Throwing null as if it were a Throwable value.
56
Java
class Test{
static String s[];
static String s1;
public static void main(String... args){
System.out.println(s.length);
System.out.println(s1.length());
throwingNull();
}
public static Object throwingNull(){
All the 3 will throw
throw null; }}
NullPointerException at runtime
Folder 14
57
Java
class Test{
public static void main(String s[]){
System.out.println(s[0]);
}}
What exception will this code throw?
• NullPointerException
• ArrayIndexOutOfBoundsException

58
Java
ClassCastException
• It inherits from RunTimeException class.
• It is thrown when we try to cast an object to a subclass
of which it is not an instance.
• Example :
general.Person st
= new student.Student(“Mary");
teacher.Teacher teacher
=(teacher.Teacher)st;

• Generates ClassCastException at runtime


59
Java
ExceptionInInitializerError
• A static initializer cannot throw any exception. A
compiler will throw an error in case it is done explicitly.
• class X{
static{throw new
RuntimeException(); }…}
// compilation error
• But some exceptions are caught only at runtime. In such
cases when the static block throws a runtime exception,
ExceptionInInitializerError is thrown by JVM.
• ExceptionInInitializerError is a subclass of
Error. 60
Java
•Example:

class Test {
static int [] x = new int[5];
static { x[5] = 5; }
public static void main(String []
args) { }}
JVM throws:
Exception in thread "main"
java.lang.ExceptionInInitializerError
Caused by:
java.lang.ArrayIndexOutOfBoundsException
at Test.<clinit>(Test.java:3))
Folder 15 61
Java
StackOverflowError
• This is a subclass of Error
• JVM throws this when a stack overflow occurs because
an application ‘recurses’ too deeply.
• Example:
public static void main(String[] s){
main(s); }
• JVM throws StackOverflowError when the
above program is executed.

62
Java
NoClassDefFoundError
• This is a subclass of Error
• This is thrown if the Java Virtual Machine or a
ClassLoader instance tries to load in the definition of a
class (as part of a normal method call or as part of
creating a new instance using the new expression) and
no definition of the class could be found.
• This is probably the most common exception we have
encountered right from day 1 of our java classes.
• What happens if you try to execute a class that is not in
your classpath? JVM throws :
Exception in thread "main"
java.lang.NoClassDefFoundError: Test
63
Java
Assertions
int getPercent(){
int tot=0;
for(int
i=0;i<mark.length;i++){
if( mark[i]<0 || mark[i]>100)
return -1;
else
tot=tot+mark[i]; }

return (tot/mark.length);
}

Code I added for


debugging. Must
remember to take it off
before deployment. 64
Folder 16 Java
Assert
• Assertion allows you to put in debugging
statements without worrying about taking them
off when you are done.
• Syntax : 2 forms
c) assert (condition);
d) assert(condition): statement
returning a string;
Condition must evaluate to a boolean
value.

65
Java
public static class StudentMark{
public int getPercent(){
assert(semesterMarks>=0 && MAX_MARKS>0);
return ((semesterMarks*100)/MAX_MARKS);
}
…}
• If the condition in the assert statement is not true an
AssertionError is thrown at runtime.
• In case you want a string printed instead of JVM’s
default assertion message you could use the second
syntax.
assert(semesterMarks>=0 && MAX_MARKS>0):”
erroneous semesterMarks or MAX_MARKS “;
Folder 17
66
Java
Assertion enabling
• assert was not a keyword in versions prior to 1.4.
• The 1.4 compiler needed to be told explicitly to
compile with assertion enabled for 1.4 (using assert as
keyword) –
• javac -source 1.4 classname.java
• In the 1.5 compiler, assertion is 
automatically enabled. 
• To enable assertion at runtime :
java -ea classname or
java -enableassertions classname
67
Java
Now I understand ! During
development I need to run the code
associated with StudentMark class
with assertion enabled to watch for
AssertionErrors. I need not worry
about removing code I added for
assertions because during normal
execution, code will be executed
without the assertion enabled.
Very ingenious indeed!

68
Java
Assertion disabling
• Assertions are disabled by default during runtime.
• But in case where we want to selectively enable and
disable, the following command is handy:
• java -da classname
Or java -disableassertions classname
• To selective enable and disable:
a)java -ea -da:x.X Y
Assertion disabled only for x.X class
b)java –ea –da:x… Y
Assertion disabled only for entire package x and all of
its sub packages.
69
Java
When (not) to use assertions
• Don’t use assertions to
2. To validate public method arguments. But use it to
validate private method arguments.
3. To validate command line arguments
4. In switch-case statement of public method for cases
you never know.
Ex: switch(a){case 1: //something
case 2: //something
default: assert false;
//not advisable in public method
}
70
Java
• Never use assertion to change a values of a variable
that will affect the way the code behaves. Remember
that the code will run finally without assertions. So if
the change has an effect, then it will not be reflected
when deployed.
assert(false): method(x++);
String method(int x){x=0;}
// never do this
• An assert expression should leave the
program in the same state it was in before
the expression!

71
Java
Overriding and Exception
One of the rules for overriding which we did not look
at:
- An overridden method cannot throw new checked
exceptions or parent class exception
- It can
- either throw subclass of the exception class which
the method in the parent class throws.
- Or totally ignore the exception part.

72
Java

Potrebbero piacerti anche