05 Exception and Java IO

Download as pdf or txt
Download as pdf or txt
You are on page 1of 77

Advanced Programming Applications

Lecture 5
Exception and Java I/O

CCS2304
Exceptions

Information includes: class name – line number – exception class

2
Exceptions Types

3
System Errors

4
Exceptions

5
Runtime Exceptions

6
Checked Exceptions vs Unchecked Exceptions

• RuntimeException, Error and their subclasses are known


as unchecked exceptions.

• All other exceptions are known as checked exceptions,


meaning that the compiler forces the programmer to
check and deal with the exceptions.

7
Unchecked Exceptions

8
Unchecked Exceptions
• In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable. For example,

• A NullPointerException is thrown if you access an object


through a reference variable before an object is assigned to it;

• An IndexOutOfBoundsException is thrown if you access an


element in an array outside the bounds of the array. These are
the logic errors that should be corrected in the program.
Unchecked exceptions can occur any where in the program.

• To avoid cumbersome overuse of try-catch blocks, Java


does not mandate you to write code to catch unchecked
exceptions.

9
Exceptions Hierarchy

Exception Types

Unchecked Exception Checked Exception


could be unhandled by programmer should be handled by programmer

• Error and all its subclasses are unchecked exceptions.


• RunTimeException with all its subclasses are unchecked exceptions.
• Throwable, Exception and all its subclasses (except RunTimeException
and its subclasses) are checked exception.
10
Why do we study exceptions?
• Handling Unchecked Exceptions
– Although not mandatory, handling these exceptions will
make your program reliable, robust and error prone.

• Handling checked Exceptions


– a lot of methods in the Java API throws checked Exceptions,
especially
o Methods that reads from file.
o Methods that connect your program to a remote P.C.
o Methods that connect your program to a database (Connection
and querying)

You must handle these exceptions to use these methods

11
The Catch or Specify Requirement
• Valid Java programming language code must honor the
Catch or Specify Requirement. This means that code that
might throw certain exceptions must been closed by
either of the following:
– A try statement that catches the exception. The try must
provide a handler for the exception.
– A method that specifies that it can throw the exception. The
method must provide a throws clause that lists the
exception.

12
Catch or Declare Checked Exceptions
• Java forces you to deal with checked exceptions. If a
method declares a checked exception (i.e., an exception
other than Error or RuntimeException), you must invoke
it in a try-catch block or declare to throw the exception
in the calling method.

• For example, suppose that method p1 invokes method


p2 and p2 may throw a checked exception (Ex:
IOException), you have to write the code as shown in (a)
or (b).

void p1() { void p1() throws IOException {


try { p2();
p2(); }
}
catch (IOException ex) { (b)

}
}
13
(a)
Catching Exceptions

14
The General Form of an Exception-Handling Block
try{ class Exc2 {
// block of code to monitor for errors public static void main(String args[]) {
} int d, a;
catch(ExceptionType1 exOb) { try { // monitor a block of code.
// exception handler for ExceptionType1 d = 0;
} a = 42 / d;
catch(ExceptionType2 exOb) { System.out.println("This will not be printed.");
// exception handler for ExceptionType2 }
} catch (ArithmeticException e) {
// ... System.out.println("Division by zero.");
finally{ }
// block of code to be executed before System.out.println("After catch statement.");
try block ends }
} }

• When an Exception is caught the program is transferred automatically to


the appropriate catch block otherwise program stops.
• The goal of most well-constructed catch clauses should be to resolve the
exceptional condition and then continue as if the error had never happened.
• Finally, is always executed.

15
Three Basic Rules for Exception-Handling
1- Multiple Catch Clauses void m(int i) {
int [] x = {1,4,0,2};
• After one catch statement executes, try {
the others are bypassed. int d = 4 / x[i]; }
• Exception subclasses must come before catch(ArrayIndexOutOfBoundsExceptione)
any of their superclasses, otherwise {//}
compile error. catch(ArithmeticExceptione)
{//}
2- Exception Propagation }

• If exception is not caught at its exact public static void main (String[] args) {
level , it propagates upwards towards ExcepDemo3 n = new ExcepDemo3();
the calling method. try {
• Exception can be caught at a higher n.m(3,0); }
level. catch(ArithmeticException e) {
//code to handle Exception}
}
}
void m(int x, int y) {
int z = x / y;
}

3- You can catch an exception using a reference of its super class 16


When do you use Exceptions
• When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code

try {
System.out.println(refVar.toString());
}
catch (NullPointerExceptionex) {
System.out.println("refVaris null");
}

17
When do you use Exceptions
• It is better to be replaced by

if (refVar != null)
System.out.println(refVar.toString());
else
System.out.println("refVar is null");

18
Specifying the Exceptions Thrown by a Method

• Every method must state the types of checked


exceptions it might throw using the key word throws.
▪ Method throwing checked exception is mandatory to
declare it in method signature.
▪ Method throwing unchecked exception is optional to
declare it in method signature
The calling method for a method that declares to throw a checked
exception should
➢ surround the calling with try-catch
➢ or declare itself as throws,

19
Example: Handling The Exceptions from
method Integer.parseInt
Class Integer
public static int parseInt(String s) throws NumberFormatException
Parses the string argument as a signed decimal integer.
Throws: NumberFormatException. If the string does not contain a parsable
integer

Unchecked
Exception

Optional
try-catch

20
Creating Object of scanner to read data from a file
public Scanner(File source) throws FileNotFoundException
Constructs a new Scanner. That produces values scanned from the specified file.
Parameters:
source - A file to be scanned
Throws:
FileNotFoundException – if source is not found.

Mandatory
try-catch
checked
Exception

public static void m1 (){


File data=new File("Data.db"); public static void m1 () throws FileNotFoundException{
try{ File data=new File("Data.db");
Scanner scan =new Scanner(data); Scanner scan =new Scanner(data);
} }
catch(FileNotFoundExceptione)
{ //code to handle Exception} 21
}
When to Throw Exceptions
• An exception occurs in a method.

• If you want the exception to be processed by its caller,


you should create an exception object and throw it.

• If you can handle the exception in the method where it


occurs, there is no need to throw it.

22
Throwing Exceptions
• When the program detects an error, the program can
create an instance of an appropriate exception type and
throw it. This is known as throwing an exception.
• Here is an example,

throw new TheException();

TheException ex = new TheException();


throw ex;

23
Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius) throws
IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}

24
Throwing Exceptions Example
class Student {
private double GPA;
public void setGPA (double GPA) {
if (GPA > 4)
throw new IllegalArgumentException();
this.GPA = GPA;
} class Student {
} private double GPA;
public void setGPA (double GPA) throws Exception {
if (GPA > 4)
throw new Exception();
this.GPA = GPA;
}
}

• You can throw checked or unchecked exception using keyword throw


• Method that throws checked exceptions is mandatory to declare in its
signature using keyword throws.

25
Declaring your own exceptions
class myException extends RuntimeException { import java.io.IOException
class myException extends I0Exception {
Unchecked Checked
Exception Exception

} }

Example

class GPAException extends RuntimeException { class Student {


private int GPA;
public void setGPA(int GPA) {
} if (GPA > 4)
throw new GPAException();
this.GPA = GPA;
}
}

26
Using Finally
• For each try-catch block there can be only one finally block.
• Case 1: If an exception is thrown with a matching catch block, then the
finally block is executed after the catch block and program continues.
• Case 2: If an exception does not happen the finally block will be
executed and program continues.
• Case 3: if an exception is thrown but not caught then the finally block
will be executed after the try block , then program stops.

try {
// statement 1 Case 1: statement 1 – statement 2 – statement 3 – statement 4
}

catch (exception e) { Case 2: statement 1 – statement 3 – statement 4


// statement 2
}

finally { Case 3: statement 1 – statement 3


// statement 3
}

// statement 4
27
Java I/O Processing

28
Class File
• The File class in the java.io package represents
files.
– Create a File object to get information about a file on the
disk. (Creating a File object doesn't create a new file on your
disk)
File f = new File ("example.txt");
if (f.exists() && f.length() > 1000) {
f.delete();
}

29
The File Class
• To operate on a file, we must first create a File object
(from java.io.File).

30
Some File Methods

31
Class Scanner
• To read a file, create a File object and pass it as a parameter when
constructing a Scanner.
File f = new File("numbers.txt");
Scanner input = new Scanner(f);

32
Input Tokens
• token: A unit of user input. Tokens are separated by whitespace (spaces,
tabs, new lines).
• Example: If an input file contains the following:
23 3.14
John Smith
• The tokens in the input are the following, and can be interpreted as the
given types:
Token Type(s)
23 int, double, String
3.14 double, String
John String
Smith String

• Each call to next, nextInt, nextDouble, etc. advances the cursor to the
end of the current token, skipping over any whitespace.

33
Reading Data using Class Scanner
• A Scanner breaks its input into tokens using whitespace. (spaces,
tabs, new lines).
• The resulting tokens may then be converted into values of
different types using the various methods.

File file = new File(“data.txt”); 23 3.14 5 Tokens


Scanner input=new Scanner(file); John Smith a
int i = input.nextInt();
double d = input.nextDouble();
String s1 = input.next();
String s2 = input.next();
char x = (input.next()).charAt(0);
34
Example

35
Example

36
public float nextFloat()
• Scans the next token of the input as a float .
• This method will throw InputMismatchException if the next token
cannot be translated into a valid float value.
• If the translation is successful, the scanner advances past the
input that matched.
• If the next token matches the Float regular expression defined
above, then the token is converted into a float value.
Throws:
InputMismatchException – if the next token does not match the Float
regular expression, or is out of range
NoSuchElementException – if input is exhausted
IllegalStateException – if this scanner is closed

37
Testing Before Reading
• The preceding program is impractical because it only processes
exactly 5 values from the input file.
– Typically, the actual program would read the entire file,
regardless of how many values it contains.
• Reminder: The Scanner has useful methods for testing to see
what the next input token will be:

Method Name Description


hasNext() whether any more tokens remain
hasNextDouble() whether the next token can be
interpreted as type double
hasNextInt() whether the next token can be
interpreted as type int
hasNextLine() whether any more lines remain

38
Example

39
Example

40
Example: Reading Data From File

41
Case Study

42
Case Study

43
Writing Data Using PrintWriter
• First, you have to create a PrintWriter object for a text file as
follows:
– PrintWriter output = new PrintWriter(filename);

• If the given file does not exist, it is created.


• If the given file already exists, it will be truncated to zero size.
• Then, you can invoke the print, println, and printf methods on the PrintWriter
object to write data to a file.
• System.out is a standard PrintWriter Java object for the console.
• The close() method must be used to close the file. If this method is not invoked,
the data may not be saved properly in the file.

44
Any Questions?

45
What is an Exception
• An exception is an unwanted or unexpected event, which occurs
during the execution of a program (i.e., at run time), that
disrupts the normal flow of the program’s instructions.

• Error vs Exception

Errors Exception
Represent serious and usually Exception indicates conditions
irrecoverable conditions like that a reasonable application
library incompatibility, infinite might try to catch.
recursion, or memory leaks.
- Exceptions are the problems
- Errors are generated to indicate which can occur at runtime and
errors generated by the runtime compile time. It mainly occurs in
environment. the code written by the
developers.
- Ex: JVM is out of memory.
Normally, programs cannot
recover from errors.

46
What is an Exception
• An exception can occur for many different reasons:
– A user has entered an invalid data.
– A file that needs to be opened cannot be found.
– A network connection has been lost in the middle of
communications.

47
Exception

Exception Class Type More info about the exception

48
Exception Solving

49
Exception

50
Exception Solving

51
Exception

52
Exception Execution

53
Exception Execution

54
Exception Multicatch

55
Unknown Exception

Arrangement is important

56
Finally Block
• A finally block in Java can be used to put “cleanup” code
such as closing a file, closing connection, etc.

• A finally block is always get executed whether the


exception has occurred or not.

• Rule: for each try block there can be one or more catch
blocks, but only one finally block.

Do not executed due to


return keyword

57
Finally Block

58
Finally Block
N.B: The finally block will not be executed if the program exits
(either by calling System.exit() or by causing a fatal error that
causes the process to abort.

59
Exception Handling
• There are three main categories of exceptional conditions:
– Checked exceptions (Compile-time exceptions)
– Unchecked exceptions (Runtime exceptions)
– Errors

• A checked exception is an exception that is checked (notified)


by the compiler at compilation-time, these are also called as
compile time exceptions. These exceptions cannot simply be
ignored, the programmer should take care of (handle) these
exceptions.

• An unchecked exception is an exception that occurs at the time


of execution. These are also called Runtime Exceptions. These
include programming bugs, such as logic errors or improper use
of an API. Runtime exceptions are ignored art the time of
compilation.

• Errors represent serious and usually irrecoverable conditions like


a library incompatibility, infinite recursion, or memory leaks.
60
Exception Hierarchy

61
Java.lang Package from API Documentation

62
Difference Between Exception and Error
• Error and Exception both are subclasses of the java Throwable
class that belongs to java.lang package.

Basis of Exception Errors


Comparison
Type It can be classified into two categories All errors in Java are
(i.e., checked and unchecked). unchecked.
Occurrence It occurs at compile time or run time. It occurs at run time.

Causes It is mainly caused by the application It is mostly caused by the


itself. environment in which the
application is running.
Recoverable/Irr Exception can be recovered by using An error cannot be recovered,
ecoverable the try-catch block. should not try catch it.

63
Exception (FileNotFoundException)

64
Exception (Read File Contents)

We used a file (resource), so we should use


finally to safely close the file to prevent the
data from being lost.
65
Exception (Read File Contents)

66
Exception (Try-with-resources) (after v1.7)

Try-with-resources will automatically


close the resources.

More than one resource

67
Exception (Throws)
2

Exception Propagation
(Exception propagators)

More than one exception

68
Exception (Throws)
Any method will call readFile method
should handle the throws exceptions
either by try-catch or using throws

69
Error
Recursion error
But we don’t figure out the problem yet

70
throw keyword
• The “throw” keyword is used to create a custom exception or
error.

• The “throw” keyword in Java is used to explicitly throw an


exception from a method or any block of code. We can throw
either checked or unchecked exception.

71
throw keyword

Custom Exception

72
throw keyword

Same as previous example but we saved it inside reference

The calling method should perform try-catch

73
throw keyword

Compiler execution sequence


finally block is executed before the throw

74
Throw Vs Throws
throw throws

Used within a method (or Used with method (or constructor)


constructor) signature
Used to throw an exception explicitly Used to declare exceptions

Can only throw a single exception Can declare multiple exceptions

Followed by a throwable instance Followed by an exception class name

Cannot be used to propagate checked Can be used to propagate checked


exceptions by itself exceptions by itself

75
Exceptions

76
User-Defined Exception

checked Exception

Unchecked
Exception

77

You might also like