Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions Networking

Similar presentations


Presentation on theme: "Exceptions Networking"— Presentation transcript:

1 Exceptions Networking
Practice Session 9 Exceptions Networking

2 Exceptions

3 Exceptions Java uses exceptions to handle errors and other exceptional events. Examples: Reading a file that does not exist or is inaccessible. Dividing a number by zero. Network is down, URL does not exist. Accessing an array element at a certain index that is not within the bounds of the array.

4 Code Example public class ExceptionExample { public static void main(String[] args) { int[] a = {2, 4, 6, 8}; for(int j = 0; j <= a.length ; j++) System.out.println(a[j]); } } /* output: 2 4 6 8 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4     at spl.examples.exceptions.ExceptionExample.main(ExceptionExample.java:7) */

5 What Is an Exception? An exception is an event that occurs during the execution of a program disrupting the normal flow of instructions. When an error occurs within a method: the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

6 After a method throws an exception, the runtime system attempts to find something to handle it.
Call Stack: The ordered list of methods that had been called to get to the method where the error occurred. This is the set of possible "somethings" to handle the exception.

7 The runtime system searches the call stack for a method that contains a block of code that can handle the exception, exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. If no handler is found, the exception is thrown to the JVM, which terminates the program, and prints the exception together with its call stack to the console.

8 Exception Types There are 2 different types of exceptions:
Unchecked Exceptions: Errors: External to the application The application usually cannot anticipate or recover from them. They are indicated by Error and its subclasses.  Example:  OutOfMemoryError - the application ran out of memory

9 Runtime Exceptions: Internal to the application
The application usually cannot anticipate or recover from. Usually indicate programming bugs, such as logic errors or improper use of an API. Runtime exceptions are those indicated by RuntimeException and its subclasses. Examples: NullPointerException - the application is trying to access a null pointer (an uninitialized object). ArrayIndexOutOfBoundsException - the application is trying to access an array outside of its boundaries.

10 Checked Exceptions: Exceptional conditions that a well-written application should anticipate and recover from. Inherited from the core Java class Exception. Checked exceptions must be handled in your code (catch it), or passed to the calling code for handling (declare that your method might throw it using the throws keyword at the method signature). Example: FileNotFoundException - the application is trying to access a file that does not exist.

11 Exception Hierarchy

12 Throwing an Exception public class Clock { private int fHours, fMinutes, fSeconds; // constructors and methods //There is no need to catch IllegalArgumentException or to declare that the function throws it //since it's a RuntimeException (unchecked exception). public void setTime(int hours, int minutes, int seconds){ if (hours<1 || hours>12 || minutes<0 || minutes>59 || seconds<0 || seconds>59) throw new(IllegalArgumentException(“Invalid time”); //this code does not run if an exception occurs. fHours = hours; fMinutes = minutes; fSeconds = seconds; } }

13 Creating New Exceptions
//a class that uses our new exception public class Stack {     int elements[];     int top;          //next empty location in the elements array     // ... constructor, push(), isEmpty()     //There is no need to declare StackUnderflowException  as thrown in the method signature      //since it's a RuntimeException (unchecked exception)     public int pop() {         if (isEmpty())              throw new StackUnderflowException();         return elements[--top];     } } Create a new exception by extending Exception, or one of its subclasses. //StackUnderflowException inherits all of its parent's methods and does not add any of its own //You can also add methods to StackUnderflowException or override existing methods to change  //printing format, for example public class StackUnderflowException extends RuntimeException {}

14 Catching Exceptions A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Each catch block is an exception handler and handles the type of exception indicated by its argument, which must inherits from the Throwable class.

15 import java.io.*; public class FirstLine { public static void main(String[] args){ String name = args[0]; try{ BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readLine(); System.out.println(line); //handle FileNotFoundException }catch (FileNotFoundException e) { System.out.println("File not found: "+ name); //handle IOException }catch (IOException e) { System.out.println("Problem: " + e); } } }

16 Handling Exceptions When handling exceptions you should restore stable state and do one of the following: Change conditions and retry. Clean up and fail (re-throw exception) If an exception extends another exception and you would like to handle each separately, then the catch block that handles the sub exception should be before the catch block that handles the base exception.

17 You can let a method further up the call stack handle the exception.
Exceptions don't have to be handled in the method in which they occurred. You can let a method further up the call stack handle the exception. This is done by adding a throws clause to the method declaration. public BufferedReader openFileForReading(String filename) throws IOException{      return new BufferedReader(new FileReader(filename)); }

18 The Finally Block Comes right after all catch blocks in a try-catch clause. The code found in the finally block is always executed before exiting the try/catch block, even if an exception occurred, or a return/continue/break statement were encountered. It is usually used for cleanup code, since it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break . For more information regarding exceptions see: Oracle Exceptions Tutorial.

19 Regular try-catch. What about file.close()?
try{ BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readLine(); System.out.println(line); }catch (FileNotFoundException e) { System.out.println("File not found: "+ name); }catch (IOException e) { System.out.println("Problem: " + e); }finally{ if (file != null) { System.out.println("Closing the file:" + name); file.close(); } else { System.out.println("Unable to open file:" + name); }

20 Try-With-Resource Close() itself throws exception. This we do not handle, but instead just thrown. To solve this issue: We can catch it inside the finally block. We can use try-with-resource statements for an elegant solution.

21 Try-with-resources try (BufferedReader file = new BufferedReader(new FileReader(name));) { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readLine(); System.out.println(line); } catch (IOException e) { System.out.println("Unable to open file due to: " + e); } BufferedReader implements the interface java.lang.AutoCloseable. BufferedReader instance is declared in a try-with-resource statement. BufferedReader will be closed regardless of whether the try statement completes normally or abruptly. Normally: everything ends as expected. Abruptly: BufferedReader.readLine() throws an IOException.

22 Networking

23 Internet Protocol What is protocol? What is internet protocol?
נוהל, רשימת כללים לביצועה של פעילות מסוימת What is internet protocol? A protocol that details how data is sent and received over the internet network. What is Internet? It is a global system of interconnected computer networks. The internet is basically a network of networks. How a machine is identified? Every machine wishes to connect to the Internet, receives an IP address. IP address is a unique identifier for the machine.

24

25 What about Israel?

26 Bezeq International Line

27 Tamares Internet Line

28 IP Address IPv4: IPv6: 32bit of size Format: XXX.XXX.XXX.XXX
Where XXX is a number from 0 to 255 Each block is 8bit. Allows 232 unique addresses (≈ 4.3billion addresses). Examples: – IP address of ynet – IP address of google – IP address of IPv6: 128bit of size Format: XXXX.XXXX.XXXX.XXXX.XXXX.XXXX.XXXX.XXXX Where each XXXX consist of a hexadecimal value. 0…9, A..F 2001:4860:0000:1001:0000:0000:0000:0068:– IPv6 of ipv6.google.com 2620:0000:1CFE:FACE:B00C:0000:0000:0003 – IPv6 of Allows 2128 unique addresses.

29 IP Addresses Utilization

30

31 Domain Name System DNS: Domain Name System
DNS maps domain names to IPs. Example: Domain name: IP: Why DNS? Machines understand numbers only. Humans find it hard to remember numbers. Thus, DNS was invented. DNS Servers are found at: Each ISP has its own DNS server. Normally two separate servers. (Primary DNS/Secondary DNS) There are 13 root servers in the world.

32 Root DNS Server Map

33 Communication Model

34 TCP/IP Model Application Layer Transport Layer Internet Layer
Communication between applications Protocols: FTP – File Transfer Protocol SMTP – Simple Mail Transfer Protocol HTTP – Hyper Text Transfer Protocol BitTorrent – Peer-to-Peer file sharing protocol Transport Layer Communication between end-to-end machines. TCP – Transmission Control Protocol UDP – User Datagram Protocol SCTP – Stream Control Transfer Protocol Internet Layer Routing: Handles the way packets are sent from end machine A to end machine B. Decides which path the packet needs to take in order to be received at destination. IP – Internet Protocol Link Layer (Network Access Layer) Move packets between the interfaces of two different hosts on the same link. Protocol: MAC – Media Access Control. Physical Layer The pure hardware in any network infrastructure through it we send our bits of data. The Ethernet cables, communication satellites, copper lines, etc.

35 TCP in TCP/IP TCP/IP is the communication protocol for communication between computers on the Internet. TCP/IP stands for Transmission Control Protocol / Internet Protocol. Using this model we can transfer data between two different machines. Examples of TCP uses: Web surfing using browsers. File download using the browser. Sending s. FTP Download

36 TCP in TCP/IP TCP is used for communication between applications.
If application A wants to communicate with application B via TCP: A sends a communication request, called “handshake”. This request must be sent to an exact address. B accepts request. After the handshake between the two applications, TCP will set up a full-duplex communication between the two applications. Then both ends can send and receive data. This communication stays until one of the application closes the connection. Full-duplex communication: A can send to B. B can send to A.

37 Ports What are ports? Why ports? Each port has a unique number:
Think of them as entry/exit points to/from a machine. Why ports? Allows more than one service to be accessible at the same time on one machine. Each port has a unique number: HTTP uses port 80. (as default) FTP uses port 21. (as default) There are 64K (65536) ports to use. (from 1 to 65536) Example: ftp:// :21/

38 Sockets What? Socket Types: Java API:
A socket is an endpoint for communication between two machines. An instance can be created by the application, and used in order transfer and receive data. Socket Types: Stream Sockets – TCP Datagram Sockets – UDP Raw Sockets – ICMP (access to a lower layer protocol like IP) Java API:

39 Stream Sockets Stream sockets are used by the Transmission Control Protocol (TCP). Definition: Client Socket: Socket clientSocket = new Socket(InetAddress address, int port); Address – server IP address. Port – port of server. Server Socket: Socket serverSocket = new ServerSocket(int port); Socket clientConnection = serverSocket.accept(); Waits for a new connection. Returns a Socket object once connected. Using this new object, communication is done.

40 Stream Sockets 2. Client connects to the server using a socket with the host/ip and the port of the server. - A local port is assigned that will be used to connect to the client. Server listens at port 4444 3. the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

41 Notes on Sockets Can create more than one client socket with the same host and port! Can create only one ServerSocket with a certain port! Cannot create a ServerSocket on a local port used by another socket.

42 Transmission Control Protocol
TCP: Connection oriented protocol; a connection must be established between two sockets before transferring data: Socket A listens to a port. Socket B connects to socket A using IP:PORT. Data can be sent in either way. Connection is closed. TCP Properties: Advantages: Data sent is guaranteed to be correct. Data sent is guaranteed to be sent in full. Data sent is guaranteed to be received in same order sent. Disadvantages: Latency (lag) introduced by waiting for acknowledgements. Overhead makes the transmission slower. Overhead: All the extra data sent by the communication protocol, excluding the real data we wish to send.

43 TCP Frame Structure

44 TCP 3-Way Handshake Diagram
Host A sends a TCP SYNchronize packet to Host B Host B receives A's SYN Host B sends a SYNchronize-ACKnowledgement Host A receives B's SYN-ACK Host A sends ACKnowledge Host B receives ACK.  TCP socket connection is ESTABLISHED.

45 UDP- User Datagram Protocol
No connection between sockets required! Application A can send any data at any time without prior notification. UDP Properties: No guarantee on packet order. No guarantee if packet is received. If a packet received is corrupt, then it is discarded. UDP Advantages: Great for streaming live media (video, music). Faster transmission due to smaller overhead. UDP is used by: DNS DHCP Any Time-sensitive application.

46 UDP Frame Structure

47 The Client-Server Model
A widely used model consisting of: Server Clients Server: Provides a service of some kind. Examples: Web Server, FTP Server, DNS Server Clients: Connect to the server requesting the service. Establishing connection: The Server awaits connections. (listens to a port) The server reacts to clients requests. Example: SimpleLinePrinter (TCP server-client: server accepts one client receives msgs from it- “bye” for termination)

48 Running netstat –p when both the client and server are on the same machine should show:

49 Text Transfer In Java Reading data from Socket:
Reader Object: BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()), “UTF-8”); Reading Line: String line = bufferedReader.readLine(); Writing data to socket: Writer Object: PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true); Writing Line: printWriter.print(“my text message”); printWriter.flush();

50 Text Encoding Different computers may use different symbol representations. Text sent might be received and understood differently. Example: Sending text from Linux Windows operating systems. New line in Linux: \n New line in Windows: \r\n In order to ensure that the text sent is received correctly, both clients and server need to agree on text format. Encoding formats example: UTF-8 ANSI UCS-2

51 Examples in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(),"UTF-8")); out = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"), true); Code Examples: 02_Echo(server sends back the messages that the client sends – UTF-8 format)

52 Protocol Interface We don’t want to hold the implementation of a protocol inside the server’s code.  Protocol: How to send messages How to end transmission etc. define an interface ServerProtocol process() - for processing the received message and construct a response message isEnd() - identifies the end of a protocol Example: 03_ProtocolInterface (server sends messages and checks for end of transmission using a protocol- sends numbered messages).


Download ppt "Exceptions Networking"

Similar presentations


Ads by Google