Está en la página 1de 84

unit-v

Types of errors
Errors broadly classified into two categories.
Compile-time errors Run-time errors.

Compile-Time Errors
        Missing semicolons. Missing brackets in classes and methods. Misspelling of identifiers and keywords. Missing double quotes in strings. Use of undeclared variables. Bad references to objects. Use of = in place of == operator And so on.
3

Run-Time Errors
 Dividing an integer by zero.  Accessing an element that is out of the bounds of an array.  Attempting use a negative size of an array.  Converting invalid string to a number.  Accessing a character that is out of bounds of a string.  Trying to cast an instance of a class to one of its subclasses.  Using a null reference to access a method or a variable.  Missing input file.  And so on.

Exceptions
An exception is a run-time error.
When JRE encounters a run-time error, it creates an exception object and throws it ( i.e., informs us about an error ). If the exception object is not caught and handled properly, the JRE will display an error message as shown below and will terminate the program.
5

Ex:
class Error1 { public static void main( String arg[]) { int a=10; int b=5; int c=5; int x= a/(b-c); System.out.println( x= +x); int y=a/(b+c); System.out.println( y= +y); } } Java.lang.ArithmeticException: /by zero at Error1.main.( Error1.java :10)
6

If we want the program to continue with the execution of the remaining code, then we should catch the exception object thrown by the JRE and then display an appropriate message for taking corrective action. This task is known as exception handling.

Exception Handling
Performing action in response to exception Examples
Exit program (abort) Ignore exception Deal with exception and continue
Print error message Request new data Retry action
8

Benefits of exception handling


It allows us to fix the error. It prevents program from automatically terminating. Separates Error-Handling Code from Regular Code.
Conventional programming combines error detection, reporting, handling code with the regular code, leads to confusion.

Exception-Handling Fundamentals
Exceptions can be generated by the Java run-time system, or they can be manually generated. An exception can be caught to handle it or pass it on. Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally.

10

Exception-Handling Fundamentals
Program statements which might generate exceptions are kept inside a try block. If an exception occurs within the try block, it is thrown. Code within catch block catches the exception and handles it. System generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw Any exception that is thrown out of a method must be specified by a throws clause.
11

Java Exception class hierarchy


EOFException IOException FileNotFoundException

Exception

ArithmeticException ArrayIndexOutOfBoundsException RuntimeException StringIndexOutOfBoundsException

Object

Throwable NumberFormatException NullPointerException VirtualMachineError Ex: Stack overflow Checked Unchecked

Error

12

All exception types are subclasses of the built-in class Throwable. Throwable has two subclasses, they are Exception
Represents exceptions that an user program might want to catch.
Ex:- IOExceptions, RuntimeExceptins ets.

Error
Represents exceptions that are not expected to be caught by user program. i.e. Stack overflow

13

IOExceptions: The Subclasses IOException represent exceptions that can occur during the processing of input and output statements. RuntimeExceptions: The subclasses of RuntimeException represent exceptions that arise during the processing of bytecode that represent a program.

14

Categories Of Exceptions
Unchecked exceptions Checked exception

15

Characteristics Of Unchecked Exceptions


The compiler doesnt give any error even if we do not catch these exceptions. No try-catch block or throws required by the compiler. Examples: All the subclasses of RuntimeException and Error are unchecked exceptions.

16

Checked Exceptions
The compiler gives an error if we do not catch these exceptions. You must use a try-catch block or throws Example: Subclasses of IOException are checked exceptions.

17

Syntax of exception handling code

18

Using try and catch


 The catch clause should follow
immediately the try block Once an exception is thrown, program control transfer out of the try block into the catch block. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.
19

Example

Output:
Division by zero. After catch statement.
20

Multiple catch Clauses


If piece of code generates more than one exception, then we use multiple catch clauses. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After one catch statement executes, the others are bypassed.
21

Example

22

Caution
Remember that, exception subclass must come before any of of their superclasses Because, a catch statement that uses a superclass will catch exceptions of that type plus any of its subclasses. So, the subclass would never be reached if it comes after its superclass For example, ArithmeticException is a subclass of Exception Moreover, unreachable code in Java generates error.
23

Example

24

Nested try Statements


A try statement can be inside the block of another try. If an inner try statement does not have a catch, then the next try statements catch handlers are inspected for a match. This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception.
25

Example

26

Output
When no parameter is given:
Divide by 0: java.lang.ArithmeticException: / by zero

When one parameter is given


a=1 Divide by 0: java.lang.ArithmeticException: / by zero

When two parameters are given


a=2 Array index out-of-bounds: java.lang.ArrayIndexOutOfBoundsException

27

Termination or Resumptive Models


When an exception is thrown, control transfers directly to the catch block that handles the error. Unless the programmer explicitly reinvokes the same method, control will not return to the point at which the error occurred. This is referred to as the termination model of exception handling. There exist other languages that permit control to be returned to the point of error. This is referred to as the Resumptive model of exception handling.
28

throw
So far, you have only been catching exceptions that are thrown by the Java run-time system. It is possible for your program to throw an exception explicitly. General form throw TrrowableInstance Here, TrrowableInstance must be an object of type Throwable or a subclass Throwable. Simple types, such as int or char, as well as nonThrowable classes, such as String and Object, cannot be used as exceptions. There are two ways to obtain a Throwable objects: Using a parameter into a catch clause 29 Creating one with the new operator

Example
class Demo { public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } static void demoproc() { try { NullPointerException ne=new NullPointerException("demo"); throw ne; } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; // rethrow the exception } }
30
}

if(withdrawAmount < 0) throw new InvalidArgumentException (Error Negative withdraw amount); else balance -= withdrawAmount;

new is used to construct an instance of NullPointerException. All of Javas built-in run-time exceptions have at least two constructors:
One with no parameter Another one that takes a string parameter.

The string parameter is used to describe exception.


31

throws
If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception
type method-name parameter-list) throws exception-list { // body of method }

It is not applicable for Error or RuntimeException, or any of their subclasses


32

finally
finally creates a block of code that will be executed after try/catch block has completed and before the code following the try/catch block. The finally clause is also executed whenever the control is about to return to the caller from inside a try/catch block, via an explicit return tatement. finally clause will execute whether or not an exception is thrown. The finally clause is optional. Each try statement requires at least one 33 catch or a finally clause.

Example
class FinallyDemo { public static void main(String args[]) { try { int c=2/0; } catch (ArithmeticException e) {
System.out.println("Exception caught"); }

finally{ System.out.println("finally block"); } System.out.println("after finally block"); }


34

Javas Built-in Exceptions


Java defines several exception classes in java.lang package and java.io package. Unchecked Exceptions defined in java.lang

Exception
ArithmeticException byArrayIndexOutOfBoundsException NegativeArraySizeException ClassCastException NullPointerException NumberFormatException StringIndexOutOfBounds

Meaning
Arithmetic error, such as dividezero. Array index is out-of-bounds. Array created with a negative size. Invalid cast. Invalid use of a null reference. Invalid conversion of a string to a numeric format. Attempt to index outside the bounds

of a string.

35

NumberFormatException
Ex:- int n=Integer.parseInt(a);

ClassCastException
Ex:- Here Ball is base class and SoftBall is derived class.
Ball b = new SoftBall(); SoftBall s = (SoftBall)b; Ball b=new Ball(); SoftBall s=(SoftBall)b;

 Note that the second statement throws an exception


of type ClassCastException if the object referenced by the b variable isnt a BaseBall object.
36

Checked exceptions defined in java.io


Exception
FileNotFoundException EOFException

Meaning
File is not found End of File Exception. ( occurs when you try to read beyond EOF) when a file is opened for writing on a drive with insufficient space, or a read-only file is opened for writing.
37

IOException

Creating Your Own Exception Subclasses


Javas built-in exceptions handle most common errors. It is also possible to create your own exception types to handle situations specific to your applications. User-defined exceptions are created by extending Exception class. The Exception class does not define any methods of its own.
38

Contd..
It inherits all the methods provided by Throwable. Thus, all exceptions, including those that you create, contain the methods defined by Throwable.

39

The Methods Defined by Throwable Method


void printStackTrace( ) String toString( ) containing description of the method is called by outputting a String getMessage( )

Description
Displays the stack trace. Returns a String object exception name and exception. This println( ) when Throwable object. Returns a description of the exception.

40

class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } } class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); }
41

public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }

Output:
Called compute(1) Normal exit Called compute(20) Caught MyException[20]
42

Multithreaded Programming
MultiTasking




Process Based Thread Based

43

Process Based Multitasking


The process-based multitasking is the feature that allows your computer to run two or more programs concurrently.
For example, process-based multitasking enables you to run the Java compiler at the same time that you are using a text editor.

A process is a program in execution. A program becomes process when an executable file is loaded into memory. Two common techniques for load executable file are double-clicking an icon representing the executable file and entering the name of the executable file on the command line(ex:-java demo /a.out) 44 Each process contains its own address space.

Process Based Multi Tasking


Task A Task B Task C

Processor The Operating System assigns processor time to each task

45

Thread Based Multitasking


The thread-based multitasking is the feature that allows your computer to run two or more parts of a program concurrently.
For example, a text editor can format text at the same time that it is printing.

Thread is a part of the program that is executed independently of other parts of a program.

46

Thread Based Multitasking


Task A Processor A Threading library creates threads and assigns processor time to each thread
47

T2 T1 T0

Multitasking Improves Performance


Single task
p1

Two tasks

48

Context switch
Context switch moves CPU form one process to another process. Switching the CPU to another process requires a state save of the current process and a state restore of a different process. While switching the state of the process will be stored in PCB( Process Control Block ).
49

Difference b/w Multithreading and Multitasking

Multithreading
Thread is the smallest unit of code of that is executed All threads share common address space Context switching is low cost high cost Thread is light weight task Interthread communication is inexpensive is It is under the control of java control of java

Multitasking
Process is the smallest unit that is executed. Each process has its own address space Context switching is

process is heavy weight task Interprocess communication expensive. It is not under the

50

Thread Life Cycle( States)

51

Thread States
 When a thread is first created, it does not exist as an independently executing set of instructions. Instead, it is a template/structure from which an executing thread will be created. This state is refer to born state.

 When the thread start method is called, the thread is now enter the ready state.  When the system assigns a processor to the thread , the thread is in the running state.  A thread enters the dead state when its run method completes or terminates.
52

Contd..
 The running thread will enter the block state when it issues an input or output request.  The running thread will enter waiting state when wait method is called. One thread in the waiting state will become ready when notify method is called. Every thread in the waiting state will become ready when notifyAll method is called.
53

Thread priorities
Every thread has a priority( integer value) which can be increased or decreased by calling the setPriority() method. Threads priority is used to decide when to switch from one running thread to the next.
Thread.MIN_PRIORITY is the minimum priority (defined 1) Thread.MAX_PRIORITY is the maximum priority (defined as 10) When a thread is created, it is given a default priority of 5 defined as Thread.NORM_PRIORITY.

54

Contd.. The rules that determine when a context switch takes place are :
A thread can voluntarily relinquish control. This is done by explicitly issuing, sleeping, waiting or blocking on pending I/O. In this scenario, all other threads are examined, and the highestpriority thread that is ready to run is given the CPU. A thread can be preempted by a higher-priority thread. In this case, a higher-priority thread acquires the processor from lowerpriority process. No matter what it is doing. Basically, as soon as a higher-priority thread wants to run, it does. This is called preemptive multitasking.

55

If two threads with the same priority are competing for CPU cycles, those threads are time-sliced or timeshared automatically in round-robin fashion (Windows 98).

56

Ex:Ready Threads

57

The Thread Class and the Runnable Javas multithreading isInterface Thread class, its built upon the

methods, and Runnable interface. To create a new thread, your program will either extend Thread or implement the Runnable interface. The Thread class defines several methods that help manage threads.

58

Methods Defined by the Thread class public class Thread {


public Thread(Runnable R); // Thread R.run() public Thread(Runnable R, String threadName); public void start(); public void run(); public String getName(); public void interrupt(); public boolean isAlive(); running. final public void join(); // begin thread execution // Entry point for the thread. // obtain a threads name // Determine if a thread is still // Wait for a thread to terminate.

public void setDaemon(boolean on); public void setName(String name); // sets name to the thread public void setPriority(int level); // sets priority to the thread public static Thread currentThread(); public static void sleep(long milliseconds); //Suspend a thread for a period of time. 59 ... }

The Main Thread


When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons: It is the thread from which other child threads will be generated. Often it must be the last thread to finish execution.

60

Contd..
Although the main thread is created automatically, it can be controlled through Thread object. We can obtain a reference to a main thread by calling the method currentThread( ), which is a public static member of Thread. Its general form is shown here: static Thread currentThread( ) This method returns a reference to the thread in which it is called. Once we have a reference to the main thread, you can control it just like any other thread.
61

Ex:class CurrentThreadDemo { public static void main(String args[]) { Thread t = Thread.currentThread(); System.out.println("Current thread: " + t); // change the name of the thread t.setName("MyThread"); System.out.println("After name change: " + t); try { for(int n = 5; n > 0; n--) { System.out.println(n); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted"); } } }
62

Output:Current thread: Thread[main,5,main] After name change: Thread[MyThread,5,main]


5 4 3 2 1

Name of the thread Thread Priority

Thread group name

63

Single and Multithreaded Processes


threads are light-weight processes within a process
Single-threaded Process Threads of Execution Multiplethreaded Process

Single instruction stream

Common Address Space

Multiple instruction stream

64

Creating a Threads in java


Java defines two ways to create threads
Create a class that implements the Runnable interface. Create a class that extends Thread class.

65

I Method: Threads by implementing  class MyThread implements Runnable Runnable interface {


..... public void run() { // thread body of execution } }

Create your thread class instance: MyThread myObject = new MyThread(); Create Thread class instance by passing your thread class instance to the Thread constructor : Thread thr1 = new Thread( myObject ); Start Execution: thr1.start();

66

An example
class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); // due to implementing the Runnable interface // I can call start(), and this will call run(). t.start(); } // end main() } // end class ThreadEx2
67

II method: Extending Thread class


Threads are implemented as objects that contains a method called run()
class MyThread extends Thread { public void run() { // thread body of execution } }

Create your thread class instance: MyThread thr1 = new MyThread(); Start Execution of threads: thr1.start();
68

An example
class MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) { MyThread t = new MyThread(); // due to extending the Thread class (above) // I can call start(), and this will call // run(). start() is a method in class Thread. t.start(); } // end main() } // end class ThreadEx1

69

join()
Often we want the main thread to finish last. It does not happen automatically. We uses join( ) to ensure that the main thread is the last to stop. final void join( ) throws InterruptedException This method waits until the thread on which it is called terminates.

70

Creates thread t Main thread

Calls t.Join() Main thread suspends execution

Thread t terminates

Main thread resumes


71

Synchronization
When two or more threads need access to a shared resource, they need some way to ensure that the resource will be used by only one thread at a time. The process by which this is achieved is called synchronization. Java provides language-level support for synchronizing threads.

72

Ex:-

Booking agent 1

Booking agent 2

..

Booking agent n

Check availability Reserve seat Check availability Reserve seat Seat reservation database Check availability Reserve seat

73

Using Synchronized Methods


Every object with synchronized methods is a monitor. Java allows one thread at a time to execute a synchronized method on the monitor/object. When the synchronized method is invoked, the object is locked. All other threads attempting to invoke synchronized methods must wait.

When a synchronized method finishes executing, the lock on the object is released. The highest priority ready thread that invoke a synchronized method will proceed.
74

Interthread Communication
Java uses wait(),notify() and notifyAll() to perform Interthread Communication.
wait( ) tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify( ). notify( ) wakes up the first thread that called wait( ) on the same object. notifyAll( ) wakes up all the threads that called wait( ) on the same object.The highest priority thread will run first.

These methods are implemented as final in Object class, as shown below.


final void wait( ) throws InterruptedException final void notify( ) final void notifyAll( )

75

Ex: An incorrect implementation of a producer and consumer problem.


class Q { int n; synchronized void produce(int n) { this.n = n; System.out.println("Produced: " + n); } synchronized void consume() { System.out.println(Consumed: " + n); } }

76

class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; } public void run() { int i = 0; while(true) { q.produce(i++); } } }
77

class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; } public void run() { while(true) { q.consume(); } } }

78

class PC { public static void main(String args[]) { Q q = new Q(); Producer p =new Producer(q); Consumer c=new Consumer(q); Thread t1=new Thread(p); Thread t2=new Thread(c); t1.start(); t2.start(); System.out.println("Press Control-C to stop."); } } Nothing stops the producer from overrunning the consumer. Similarly Nothing stops the consumer from overrunning the producer.
79

 A correct implementation of a producer and consumer problem.


class Q { int n; boolean valueSet = false; synchronized void produce(int n) { if(valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; System.out.println("produced: " + n); valueSet = true; notify(); } }

80

synchronized void consume() { if(!valueSet) try { wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } System.out.println(Consumed: " + n); valueSet = false; notify(); }

81

Daemon Threads
Each application starts with one thread the one that executes main. If the application creates no other threads, it will finish when main returns. A Daemon thread is a thread that providing service to other threads and it runs in the background.  Unlike conventional user threads, daemon threads do not prevent a program from terminating.  The garbage collection thread is one of the example of daemon thread.  When only daemon threads remain alive, the Java virtual machine process exits.  void setDaemon(boolean on) Marks this thread as either a daemon thread (true) or a user thread (false).

82

Thread Groups
ThreadGroup creates a group of threads.
Constructor ThreadGroup( String groupName);

Threads are put into thread groups for security reasons. Threads within a thread group can modify the other threads in the group. A thread cannot modify threads outside its own group. This restriction can be used to protect threads from manipulation by other threads.
83

When a thread dies, the Thread object is removed from its group. We can use a threadgroup to manage threads in the group.

84

También podría gustarte