Upload
mina-fawzy
View
218
Download
0
Embed Size (px)
Citation preview
7/27/2019 Lecture 7 Exceptions and Sockets
1/34
Lecture 7Exceptions
7/27/2019 Lecture 7 Exceptions and Sockets
2/34
Exception
An exception is an event, whichoccurs during the execution of a
program, that disrupts the normal flow
of the program's instructions
7/27/2019 Lecture 7 Exceptions and Sockets
3/34
Java's exception handling can be used to deal with potentially serious or
unpredictable error conditions.
Examples of serious errors that could occur within a Java program are as follows:
a program tries to read past the end of a data file;
a program cannot find a specified input file;
a program tries to connect to a website using an invalid address;
a program runs out of memory;
a method tries to access an array element whose index is larger than the upper limit ofthe array;
an overflow condition occurs when the result of some arithmetic operation exceeds the
limit for the primitive data types involved;
a program expecting to read a file of integers finds a string value in the file;
a method expecting an object reference encounters a null reference instead.
7/27/2019 Lecture 7 Exceptions and Sockets
4/34
Exception handling
Exception handling in its simplest form, it works like this:
1. When Java system detects an error, it stops the normal flow of programexecution.
We say here the code throws an exception.
2. A special kind ofJava object, known as an exception object, is created.
This object holds some information about what has gone wrong.
There are different kinds of exceptions for different sorts of error conditions.
3. Control is transferred from the part of your program where the error occurred toan exception handler, which deals with the situation.
We say here that the exception handlercatches the exception.
4. The exception object is available to the exception handler code and can be usedto help decide on the appropriate action.
7/27/2019 Lecture 7 Exceptions and Sockets
5/34
Throwable Class
The Throwable represents the most general class for describing exceptions.
The subclasses ofThrowable can be divided into three main groups:
7/27/2019 Lecture 7 Exceptions and Sockets
6/34
Error Class
The Error class and its subclasses.
The class Error describes exceptions that occur when someinternal Java error has happened for example, the Java systemhas run out of memory. Such errors are rare and there is little thata programmer can do about them.
7/27/2019 Lecture 7 Exceptions and Sockets
7/34
Exception Class The Exception class and its subclasses, excluding the RunTimeException.
Exception and its subclasses can be monitored and acted on. Some of these are defined
as checked exceptions. Programmers MUSTinclude code to declare or handle anychecked exceptions that might occur. The Java compiler will report an error if this hasnot happened.
7/27/2019 Lecture 7 Exceptions and Sockets
8/34
RuntimeException The RunTimeException class and its subclasses.
These exceptions need not be caught or declared. They are called unchecked
exceptions. Java contains facilities for catching the exceptions that can occurduring the running of a program. are normally due to programming errors these
should be eradicated by proper design, good programming style and exhaustive
testing.
7/27/2019 Lecture 7 Exceptions and Sockets
9/34
Examples ofchecked exceptions:
EOFException occurs when a program
attempts to read past the end of a file.
FileNotFoundException can occur whena program attempts to open or write to an
existing file, but the file is not found.
MalformedURLException indicates that
an invalid form of URL (such as a website
address) has occurred.
7/27/2019 Lecture 7 Exceptions and Sockets
10/34
Examples ofunchecked exceptions(subclasses ofRunTimeException):
ArrayIndexOutOfBoundsException occurs when a program tries to access an
array with an index outside the valid limits.
ArithmeticException arises when an illegal arithmetic condition occurs, such
as an attempt to divide an integer by zero.
NumberFormatException can be caused by an application expecting to read a
number of some sort, when the data does not have the appropriate format.
NullPointerException happens when an application attempts to use null in acase where an object is required: for example, invoking a method on a null
reference.
7/27/2019 Lecture 7 Exceptions and Sockets
11/34
Declaring and handling Checked
exceptions
For checked exception, you must do one of two things:
(1) Catch the exception and deal with it within the method, using a try-catchstatement (Handling exceptions).
(2) Declare in the method header that an exception may be thrown
in this case you do not handle the exception within the method, but simply
( pass it on)
7/27/2019 Lecture 7 Exceptions and Sockets
12/34
Handling Exception
Using Try...Catch
7/27/2019 Lecture 7 Exceptions and Sockets
13/34
Handling Exceptions To deal with an exception that has been thrown, we use atry-catch
statement.
Example: updating the previous code we wrote to read from a file
Notice the difference
it is best to be as specific as possible about the type of
exception you expect to be generated. For example, it is
usually a bad idea to do this in the above code.
When this handler code is executed, the variable within
the catch clause will contain a reference to the
exception object that has been thrown.
7/27/2019 Lecture 7 Exceptions and Sockets
14/34
Handling ExceptionsIf more than one type of exception is possible, we canadd additional catch clauses, like this:
The code in the try block is
executed;if an exception is thrown the
try block is exited and theappropriate exception
handler code,if any, is executed. The
exception handling codethat is executed depends on
which exception has beenthrown.
7/27/2019 Lecture 7 Exceptions and Sockets
15/34
Handling Exceptions It is possible and sometimes helpful to have more than one try statement
within a method. This clearly defines the area of code where each exception
is expected to arise:
7/27/2019 Lecture 7 Exceptions and Sockets
16/34
Finally Cause One of the things we often want to do after an exception has occurred is to
'clean up' by releasing any resources such as memory or files that a methodhas been using before the exception was thrown. This allows these resources
to be used by other parts of the program or other programs.
To deal with this, Java provides another facility in the try statement thefinally clause.
Code in the finally clause will be executed at the end of the try statement,
whether or not execution was interrupted by an exception.
7/27/2019 Lecture 7 Exceptions and Sockets
17/34
Passing Exceptions
7/27/2019 Lecture 7 Exceptions and Sockets
18/34
Declaring exceptions in the method header
When declaring an exception in the method header, you use the keywordthrows followed by the type of exception expected.
Examples:
Example1: If the method unexpectedly came to the
end of the file when expecting to read more data, then
the method would generate an exception of type
EOFException.
Example2:A method may be capable of generating
more than one type of checked exception. In this case
you need to list all the possible types
Example3: If some or all of the possible exception
types in a list are subclasses of a particular exception
class, it may be possible to shorten the list.This works because EOFException and
MalformedURLException are subclasses of
IOException.
7/27/2019 Lecture 7 Exceptions and Sockets
19/34
What happens if the code throws an exception that is not handled in any trycatch statement within the method?
Answer: then the exception will be passed to the method that invoked thismethod. Any exception not handled in a particular method will be passed up achain of invoking methodsto a higher level, until an appropriate exceptionhandler is found. This is known as propagating the exception, as shown in figure.
Ifno handler exists at any level for this exception, then the program terminateswith an error message.
7/27/2019 Lecture 7 Exceptions and Sockets
20/34
Creating Exceptions
7/27/2019 Lecture 7 Exceptions and Sockets
21/34
Creating Exception An exception is just an object - in order to create one, create a new class
that inherits from one of the Exception classes that are provided as part ofthe Java class library.
Most exceptions have two constructors
a constructor with no arguments
and a one-argument constructor that allows for a more detailed error message.
For example:
7/27/2019 Lecture 7 Exceptions and Sockets
22/34
Defensive Programming
7/27/2019 Lecture 7 Exceptions and Sockets
23/34
Defensive programming
There are techniques to deal with potential errors, which are based on
anticipating the conditions under which errors will occur.
For example,
to have a method return a value indicating whether the error condition was met
when performing the code within the method.
7/27/2019 Lecture 7 Exceptions and Sockets
24/34
Defensive programming
It is appropriate when the potential error is predictable and localized .
e.g. , checking that a queue is not full before attempting to add a new element.
However, it has some drawbacks.
If there is a lot of error checking, this can obscure the main purpose of the method.
It is ad-hoc - different programmers may take different approaches to handling errors
It may not be possible for a method to return a value indicating that an error has occurred- for example, if the method already returns a result
Exception handling
It is intended for conditions that are
Unpredictable: caused by external events out of the control of the program, such as file
errors Serious: requiring the program to be terminated
Widespread: occurring at many places in the program, making it hard to check explicitly
Exception handling is typically much slower in execution than standard error-handling techniques - this is a reason to use it sparingly.
7/27/2019 Lecture 7 Exceptions and Sockets
25/34
Example: dealing with a divide-by-zero
problem (pseudo-code)
exception handling defensive programming
7/27/2019 Lecture 7 Exceptions and Sockets
26/34
Programming with
Sockets
7/27/2019 Lecture 7 Exceptions and Sockets
27/34
What Is a Socket?
A socket is one end-point of a two-way communication link between two
programs running on the network. Socket classes are used to represent theconnection between a client program and a server program. The java.net
package provides two classes--Socket and ServerSocket--that implement the
client side of the connection and the server side of the connection,respectively.
Each socket is unique since it consists of an IP address and a port number.
7/27/2019 Lecture 7 Exceptions and Sockets
28/34
Sockets on the server
The creation of sockets is approached differently. This is because the server does notnormally initiate a connection rather, it waits for a client to request a connection.
Hence it cannot create a socket until it knows the address of the client that wants to establish a
connection The class ServerSocket is used within a server for setting up sockets. The class has
two important constructors
ServerSocket(int) & ServerSocket(int, int)
The port number should be given to the single argument constructor, while the (port_number,max_number_of_clients) should be given to the 2 arg. constructor. For ex.:
ServerSocket ss = new ServerSocket(80); //port 80
ServerSocket ss = new ServerSocket(80, 30); //port 80, max clients is 30
Once a ServerSocket object is created, the server will wait for clients to request aconnection. When a connection is made, a socket linked to the client is created; this isachieved via the accept method. For example:
7/27/2019 Lecture 7 Exceptions and Sockets
29/34
Sockets on the client
The class Socket allows us to create sockets on the client system. The most
common Socket constructor has the form:
Socket(String, int)
You have to put the address in the String part, and the port number in the int part. For
ex.:
Socket s = new Socket("catalogue.acme.co.uk", 4000);
Socket s = new Socket("199.200.34.123", 4000);
Communication between clients and a server is achieved by input/output streams.
Each socket has an associated input stream and output stream the methodsgetInputStreamand getOutputStreamgive access to these streams. For ex.:
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
These streams can then be used to send and receive data, using a similar approach to
writing and reading files.
7/27/2019 Lecture 7 Exceptions and Sockets
30/34
In programming servers and clients you should bear in mind that:
A connection is a linked pair of sockets:
at the server end, the socket has the address of the client and a
suitable port number for the service required by the client; at the client end, the socket has the address of the server and the
same port number as the server for the particular service required;
The InputStream entering the client receives data from the OutputStream leaving
the server and the InputStream entering the server receives data from the
OutputStream leaving the client.
7/27/2019 Lecture 7 Exceptions and Sockets
31/34
HOW to send/receive data between a serverand a client:
CLIENT program:
1 - Create socket (Server IP &Server port#)
2 - Open in/out streams
PrintWriter, BufferedReader, BufferedWriter +
sockets getOutputStream(), getInputStream()
- Send/receive data
- Close in/out streams
3 - Close socket
SERVER program
1- Create ServerSokcet object with a port number
2- Open socket use accept() of ServerSocket object3 - Open in/out streams
PrintWriter, BufferedReader, BufferedWriter +
sockets getOutputStream(), getInputStream()
- Send/receive data
- Close in/out streams
4- Close socket
7/27/2019 Lecture 7 Exceptions and Sockets
32/34
Server CodeA simple client
server example
The server code!
USING
PrintWriter
Summary of Server program
1- Create ServerSokcet object
2- Open socket use accept()
3 - Open in/out streams
- Send/receive data
- Close in/out streams
4- Close socket
Dont forget to:
- Import appropriate libs
- handle errors!
7/27/2019 Lecture 7 Exceptions and Sockets
33/34
Client Code
A simple clientserverexample
The client code!
Summary of Client program
1- Create socket with IP/port#
2 - Open in/out streams
- Send/receive data
- Close in/out streams
3- Close socket
Dont forget to:
- Import appropriate libs
- handle errors!
Note:
you should run the serverbefore running theclient! (Why??)
7/27/2019 Lecture 7 Exceptions and Sockets
34/34
END