Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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
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
Exception
Object
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
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
18
Example
Output:
Division by zero. After catch statement.
20
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
Example
26
Output
When no parameter is given:
Divide by 0: java.lang.ArithmeticException: / by zero
27
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.
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 }
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"); }
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;
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
Contd..
It inherits all the methods provided by Throwable. Thus, all exceptions, including those that you create, contain the methods defined by Throwable.
39
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
43
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.
45
Thread is a part of the program that is executed independently of other parts of a program.
46
T2 T1 T0
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
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
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
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 ... }
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
63
64
65
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
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
Thread t terminates
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
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.
75
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
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