Académique Documents
Professionnel Documents
Culture Documents
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.
1
Common Runtime Errors
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
And more .
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 without
executing further statements:
java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)
2
Traditional way of Error Handling
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);
}
Program reaches here
else{
System.out.println( B is zero );
}
System.out.println( Program is complete );
}
}
Error Handling
Any program can find itself in unusual
circumstances Error Conditions.
3
Exceptions
An exception in Java is an object that describes
an unusual or erroneous situation
4
Uncaught Exceptions
If an exception is not caught by user program, then
execution of the program stops and it is caught by the
default handler provided by the Java run-time system
Default handler prints a stack trace from the point at
which the exception occurred, and terminates the
program
Ex:
class Exc0 {
public static void main(String args[]) {
int d = 0;
int a = 42 / d;
}
}
Output:
java.lang.ArithmeticException: / by zero
at Exc0.main(Exc0.java:4)
Exception in thread "main"
Notice how the class name, Exc0; the method name, main;
the filename, Exc0.java; and the line number, 4, are all
included in the simple stack trace.
Also, notice that the type of the exception thrown is a
subclass of Exception called ArithmeticException, which
more specifically describes what type of error happened.
5
The stack trace will always show the sequence of method
invocations that led up to the error. For example, here is
another version of the preceding program that introduces
the same error but in a method separate from main():
class Exc1{
static void subroutine(){
int d = 0;
int a = 10 / d;
}
public static void main(String args[]){
Exc1.subroutine();
}
}
The resulting stack trace from the default exception
handler shows how the entire call stack is displayed:
Java.lang-ArithmeticException: / by zero at
Exc1.subroutine(Exc1.Java:4) at Exc1.main(Exc1.Java:7)
Java.lang-ArithmeticException: / by zero at
Exc1.subroutine(Exc1.Java:4) at
Exc1.main(Exc1.Java:7)
6
Exception Handling
Java has a predefined set of exceptions and errors that
can occur during execution
ignore it
handle it where it occurs
handle it in another place in the program
13
Exception Handling
If an exception is ignored by the program, the
program will terminate abnormally and produce an
appropriate message
14
7
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
8
The try Statement
To handle an exception in a program, the line that throws
the exception is executed within a try block
17
Throws
exception
Object
catch Block
Statements that
handle the exception
9
Syntax of Exception Handling Code
try {
// statements
}
catch( ExceptionType e)
{
// statements to process exception
}
..
..
Example:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code,
d = 0;
a = 42 / d;
System.out.println{"This will not be printed.");
}
catch {ArithmeticException e) { // catch divide-by-zero error
System.out.printIn("Division by zero.");
}
System.out.println{"After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
10
Finding a Sum of Integer Values Passed as
Command Line Parameters
// ComLineSum.java: adding command line parameters
class ComLineSum
{
public static void main(String args[])
{
int InvalidCount = 0;
int number, sum = 0;
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);
}
}
11
C:\>java ComLineSum 3 4 12
Number of Invalid Arguments = 0
Number of Valid Arguments = 3
Sum of Valid Arguments = 19
C:\>java ComLineSum 3 4 a
Invalid Number: a
Number of Invalid Arguments = 1
Number of Valid Arguments = 2
Sum of Valid Arguments = 7
try {
// statements
}
catch( ExceptionType1 e)
{
// statements to process exception 1
}
..
..
catch( ExceptionTypeN e)
{
// statements to process exception N
}
12
Example:
Output
C:\>java MultiCatch
a = 0
Divide by 0: java.lang.ArithmeticException: / by zero
After try/catch blocks.
13
14