0% found this document useful (0 votes)
14 views40 pages

Java Exception Handling Overview

Java exceptions allow programs to handle errors and unexpected events in an organized manner. When an error occurs, an exception object is created and passed to the runtime system. The runtime system then searches for exception handling code. Exceptions can be caught and handled through try/catch blocks. Checked exceptions must be caught or declared in a method signature using throws, while unchecked exceptions can be caught or allowed to propagate. Programmers can define their own custom exception classes by subclassing Exception or RuntimeException.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views40 pages

Java Exception Handling Overview

Java exceptions allow programs to handle errors and unexpected events in an organized manner. When an error occurs, an exception object is created and passed to the runtime system. The runtime system then searches for exception handling code. Exceptions can be caught and handled through try/catch blocks. Checked exceptions must be caught or declared in a method signature using throws, while unchecked exceptions can be caught or allowed to propagate. Programmers can define their own custom exception classes by subclassing Exception or RuntimeException.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

OOPS WITH JAVA

KIRTI MATHUR
Exception & I/O Handling

2
WHAT IS AN EXCEPTION?

• Exception is shorthand for the phrase "exceptional


event."
• An exception is an event that occurs during the execution
of a program that disrupts the normal flow of
instructions.
• Many kinds of errors can cause exceptions
– Hardware errors, like a hard disk crash,
– Programming errors, such as trying to access an out-
of-bounds array element.

3
PROCESS IN JAVA WHEN ERRORS HAPPEN

• When an error occurs within a Java method, the method


creates an exception object and hands it off to the
runtime system.
• The exception object contains information about the
exception, including its type and the state of the
program when the error occurred.
• The runtime system is responsible for finding some code
to handle the error.
• Creating an exception object and handing it to the
runtime system is called throwing an exception.

4
WHY USING EXCEPTIONS?

• Java programs have the following advantages over


traditional error management techniques:
• Separate error handling code from “regular” code.
• Propagate errors up the call stack
• Group error types and error differentiation

5
Exception -Terminology

When an error is detected, an exception is thrown

Any exception which is thrown, must be caught by and exception handler

If the programmer hasn't provided one, the exception will be caught by a catch-all
exception handler provided by the system.
The default exception handler may terminate the application.

Exceptions can be rethrown if the exception cannot be handled by the block which caught the exception

Java has 5 keywords for exception handling:

try
catch
finally
throw
throws

6
Exceptions -Checked and Unchecked

Java allows for two types of exceptions:


Checked.
If our code invokes a method which is defined to throw checked exception, then
code MUST provide a catch handler
The compiler generates an error if the appropriate catch handler is not present
Unchecked
These exceptions can occur through normal operation of the virtual machine.
We can choose to catch them or not.
If an unchecked exception is not caught, it will go to the default catch-all
handler for the application
All Unchecked exceptions are subclassed from RuntimeException

7
Exceptions –Syntax(1/2)

try
{
// Code which might throw an exception
// ...
}
catch(FileNotFoundException x)
{
// code to handle a FileNotFound exception
}
catch(IOException x)
{
// code to handle any other I/O exceptions
}

8
Exceptions –Syntax(2/2)

catch(Exception x)
{
// Code to catch any other type of exception
}
finally
{
// This code is ALWAYS executed whether an exception was thrown
// or not. A good place to put clean-up code. ie. close
// any open files, etc...
}

9
Exceptions -Defining Checked exceptions

Any code which throws a checked exception MUST be placed


within a try block.
Checked exceptions are defined using the throws keyword in the
method definition:
public class PrintReader extends Reader
{
public int read() throws IOException
[...]
public void method1()
{
PrintReader aReader;
[... initialize reader ...]
try
{int theCharacter = [Link]();
}
catch(IOException x)
{
[...]
10
Exceptions -throwing multiple exceptions

Each try block can catch multiple exceptions.

Start with the most specific exceptions


• FileNotFoundException is a subclass of IO Exception
• It MUST appear before IOException in the catch list

public class MyClass{

public int computeFileSize()

throws IOException, ArithmeticException

[...]

public void method1()

MyClass anObject = new MyClass();

try{

int theSize = [Link]();


11
Each try block can catch multiple exceptions.
Start with the most specific exceptions
•FileNotFoundException is a subclass of IO Exception
•It MUST appear before IOException in the catch list

public class MyClass{


public int computeFileSize()
throws IOException, ArithmeticException
[...]
public void method1()
{
MyClass anObject = new MyClass();
try{
int theSize = [Link]();
}
catch(ArithmeticException x)
{
// ...}
catch(IOException x)
{
// ...

12
• Java exceptions must be instances of Throwable or any Throwable descendant.
• We can create subclasses of the Throwable class and subclasses of our
subclasses.
• Each "leaf" class (a class with no subclasses) represents a specific type of
exception and each "node" class (a class with one or more subclasses)
represents a group of related exceptions

13
How to define Own Exceptions?

To define our own exception we must do the following:

Create an exception class to hold the exception data.


Our exception class must be subclass "Exception" or another exception class
Note: to create unchecked exceptions, subclass the RuntimeException
class.
Minimally, our exception class should provide a constructor which takes the
exception description as its argument.

To throw our own exceptions:

If our exception is checked, any method which is going to throw the exception
must define it using the throws keyword
When an exceptional condition occurs, create a new instance of the
exception and throw it.

14
Java Exception Handling Sample Code

package [Link];
public class MyExceptionHandle {
public static void main(String a[]){
try{
for(int i=5;i>=0;i--){
[Link](10/i);
}
} catch(Exception ex){
[Link]("Exception Message: "+[Link]());
[Link]();
}
[Link]("After for loop...");
}
}

15
What is throws?

• The 'throws' clause in java programming language is belongs to a method to


specify that the method raises particular type of exception while being executed.
• The 'throws' clause takes arguments as a list of the objects of type 'Throwables'
class.
• Anybody calling a method with a throws clause is needed to be enclosed within
the try catch blocks.

16
What is throw?

• Use 'throw' statement to throw an exception or simply use the throw clause with
an object reference to throw an exception.
• The syntax is 'throw new Exception();'. Even we can pass the error message to
the Exception constructor

17
What is throw?

package [Link];
public class MyExplicitThrow {
public static void main(String a[]){
try{
MyExplicitThrow met = new MyExplicitThrow();
[Link]("length of JUNK is "+[Link]("JUNK"));
[Link]("length of WRONG is "+[Link]("WRONG"));
[Link]("length of null string is "+[Link](null));
} catch (Exception ex){
[Link]("Exception message: "+[Link]());
}
}
public int getStringSize(String str) throws Exception{
if(str == null){
throw new Exception("String input is null");
}
return [Link]();
}

18
package [Link];
 import [Link];
import [Link];
 
public class ExceptionHandling {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
        try{
            testException(-5);
            testException(-10);
        }catch(FileNotFoundException e){
            [Link]();
        }catch(IOException e){
            [Link]();
        }finally{
            [Link]("Releasing resources");         
        }
        testException(15);
    }
     
    19
 public static void testException(int i) throws
FileNotFoundException, IOException{
        if(i < 0){
            FileNotFoundException myException = new
FileNotFoundException("Negative Integer "+i);
            throw myException;
        }else if(i > 10){
            throw new IOException("Only supported for index 0 to 10");
        }
 
    }
 
}

20
Multithreading

What is Thread?
• Thread: single sequential flow of control within a
program
• Single-threaded program can handle one task at any
time.
• Multitasking allows single processor to run several
concurrent threads.

21
Advantages of Multithreading

• More responsive to user input – GUI application can interrupt a


time-consuming task
• Server can handle multiple clients simultaneously
• Can take advantage of parallel processing
• Different processes do not share memory space.
• A thread can execute concurrently with other threads within a
single process.
• All threads managed by the JVM share memory space and can
communicate with each other.

22
Thread Concept

Thread 1
Thread 2
Thread 3

Multiple threads on multiple CPUs

T hread 1
T hread 2
T hread 3

Multiple threads sharing a single CPU

23
Threads in Java

Creating threads in Java:

Extend [Link] class


OR
Implement [Link] interface

24
Creating threads in Java:

Extend [Link] class


• run() method must be overridden (similar to main method of sequential
program)
• run() is called when execution of the thread begins

• A thread terminates when run() returns

• start() method invokes run()

• Calling run() does not create a new thread

25
Implement [Link] interface

• If already inheriting another class (i.e., JApplet)

• Single method: public void run()

• Thread class implements Runnable.

26
Thread States
A thread can be in one of five states: New, Ready, Running, Blocked, or Finished.

yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Finished

interrupt() sleep()
Target wait()
finished

Wait for target Wait for time Wait to be


to finish out notified
Time out notify() or
notifyAll()
Blocked
Interrupted()

27
Thread States

28
Thread termination

A thread becomes Not Runnable when one of these events occurs:

• Its sleep method is invoked.

• The thread calls the wait method to wait for a specific condition
to be satisifed.

• The thread is blocking on I/O.

29
Creating Tasks and Threads

[Link] TaskClass // Client class


public class Client {
...
// Custom task class public void someMethod() {
public class TaskClass implements Runnable { ...
... // Create an instance of TaskClass
public TaskClass(...) { TaskClass task = new TaskClass(...);
...
} // Create a thread
Thread thread = new Thread(task);
// Implement the run method in Runnable
public void run() { // Start a thread
// Tell system how to run custom thread [Link]();
... ...
} }
... ...
} }

30
Thread methods
isAlive()
• method used to find out the state of a thread.
• returns true: thread is in the Ready, Blocked, or Running state
• returns false: thread is new and has not started or if it is finished.

interrupt()
f a thread is currently in the Ready or Running state, its interrupted
flag is set; if a thread is currently blocked, it is awakened and enters
the Ready state, and an [Link] is thrown.

The isInterrupt() method tests whether the thread is interrupted.

31
Java Socket Programming

• The package [Link] provides support for sockets


programming (and more).

• Typically you import everything defined in this package


with:
import [Link].*;

• Classes used in Socket Programming: InetAddress,


Socket, ServerSocket, DatagramSocket,
DatagramPacket

32
InetAddress Class

• static methods you can use to create new InetAddress objects.


• getByName(String host)
• getAllByName(String host)
• getLocalHost()

InetAddress x = [Link]( “[Link]”);


• Throws UnknownHostException

33
What are Sockets?

• Socket
• The combination of an IP address and a port number. (RFC 793 ,original
TCP specification)
• The name of the Berkeley-derived application programming interfaces (APIs)
for applications using TCP/IP protocols.
• Two types
 Stream socket : reliable two-way connected communication streams
 Datagram socket

• Socket pair
• Specified the two end points that uniquely identifies each TCP connection in
an internet.
• 4-tuple: (client IP address, client port number, server IP address, server port
number)

34
Streams- (Socket Programming)

• A stream is a sequence of characters that flow into or out


of a process.

• An input stream is attached to some input source for the


process, e.g., keyboard or socket.

• An output stream is attached to an output source, e.g.,


monitor or socket.

35
Socket Function Calls

• socket (): Create a socket


• bind(): bind a socket to a local IP address and port #
• listen(): passively waiting for connections
• connect(): initiating connection to another socket
• accept(): accept a new connection
• Write(): write data to a socket
• Read(): read data from a socket
• sendto(): send a datagram to another UDP socket
• recvfrom(): read a datagram from a UDP socket
• close(): close a socket (tear down the connection)

36
TCP Client/Server Interaction

Client
1. Create a TCP socket
2. Communicate
3. Close the connection
Server
4. Create a TCP socket
5. Repeatedly:
• Accept new connection

• Communicate

• Close the connection

37
Socket Communication

Client socket, welcoming socket (passive) and


connection socket (active)

38
JAVA TCP Sockets

• In Package [Link]
• [Link]
 Implements client sockets (also called just “sockets”).
 An endpoint for communication between two machines.
 Constructor and Methods
• Socket(String host, int port): Creates a stream socket and connects it to the specified
port number on the named host.
• InputStream getInputStream()
• OutputStream getOutputStream()
• close()

• [Link]
 Implements server sockets.
 Waits for requests to come in over the network.
 Performs some operation based on the request.
 Constructor and Methods
• ServerSocket(int port)
• Socket Accept(): Listens for a connection to be made to this socket and accepts it. This
method blocks until a connection is made.

39
Socket Programming with UDP

• UDP
• Connectionless and unreliable service.
• There isn’t an initial handshaking phase.
• Doesn’t have a pipe.
• transmitted data may be received out of order, or lost

• Socket Programming with UDP


• No need for a welcoming socket.
• No streams are attached to the sockets.
• the sending hosts creates “packets” by attaching the IP destination address
and port number to each batch of bytes.
• The receiving process must unravel to received packet to obtain the packet’s
information bytes.

40

You might also like