SlideShare a Scribd company logo
OBJECT ORIENTED  PROGRAMMING
INDEX  UNIT 4 PPT SLIDES S.NO.    TOPIC    LECTURE NO.    PPTSLIDES Concepts of exception handling     L1 L1.1TO L1.5    Benefits of exception handling    L2   L2.1 TO L2.14 Termination or resumptive models  Exception hierarchy, usage of try, catch    L3   L3.1 TO L3.7 throw, throws and finally    L 4 L4.1 TO L4.14 built in exceptions      L5  L5.1 TO 5.4 creating own exception sub classes    L6  L6.1 TO 6.4 Differences between multi threading and multitasking  L7 L7.1 TO 7.6 thread life cycle  8 creating threads, synchronizing threads    L8  L 8.1 TO 8.15 9 daemon threads, thread groups.    L9  L 9.1 TO 9.4
Concepts of exception handling Exceptions Exception is an abnormal condition that arises when executing a program. In the languages that do not support exception handling, errors must be checked and handled manually, usually through the use of error codes. In contrast, Java: 1) provides syntactic mechanisms to signal, detect and handle errors 2) ensures a clean separation between the code executed in the absence of errors and the code to handle various kinds of errors 3) brings run-time error management into object-oriented programming
Exception Handling An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: 1) when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it 2) that method may choose to handle the exception itself or pass it on 3) either way, at some point, the exception is caught and processed
Exception Sources Exceptions can be: 1) generated by the Java run-time system Fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. 2) manually generated by programmer’s code Such exceptions are typically used to report some error conditions to the caller of a method.
Exception Constructs Five constructs are used in exception handling: 1) try – a block surrounding program statements to monitor for exceptions 2) catch – together with try, catches specific kinds of exceptions and handles them in some way 3) finally – specifies any code that absolutely must be executed whether or not an exception occurs 4) throw – used to throw a specific exception from the program 5) throws – specifies which exceptions a given method can throw
Exception-Handling Block General form: try { … } catch(Exception1 ex1) { … } catch(Exception2 ex2) { … } … finally { … } where: 1) try { … } is the block of code to monitor for exceptions 2) catch(Exception ex) { … } is exception handler for the exception Exception 3) finally { … } is the block of code to execute before the try block ends
Benefits of exception handling  Separating Error-Handling code from “regular” business logic code Propagating errors up the call stack Grouping and differentiating error types
Separating Error Handling Code from Regular Code In traditional programming, error detection, reporting, and  handling often lead to confusing code Consider pseudocode method here that reads an entire file into memory readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }
Traditional Programming: No separation of error handling code ●  In traditional programming, To handle such cases, the  readFile  function must have more code to do error detection, reporting, and handling. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } }
else { errorCode = -2; }   } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }
Separating Error Handling Code from Regular Code (in Java) Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; }
catch (sizeDeterminationFailed) { doSomething; }catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively.
Propagating Errors Up the Call Stack Suppose that the  readFile  method is the fourth method in a series of nested method calls made by the main program: method1 calls  method2 , which calls  method3 , which finally calls  readFile Suppose also that method1 is the only method interested in  the errors that might occur within  readFile . method1 { call method2; } method2 { call method3; } method3 { call readFile; }
Traditional Way of Propagating Errors method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } Traditional error notification Techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1— the only  method that is interested in them.
Using Java Exception Handling method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } Any checked exceptions that can be thrown within a method must be specified in its throws clause.
Grouping and Differentiating Error Types Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy An example of a group of related exception classes in the Java platform are those defined in java.io.IOException and its descendants IOException is the most general and represents any type of error that can occur when performing I/O Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk.
A method can write specific handlers that can handle a very specific exception The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. catch (FileNotFoundException e) { ... }
A method can catch an exception based on its group or general type by specifying any of the exception's super classes in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument. // Catch all I/O exceptions, including // FileNotFoundException, EOFException, and so on. catch (IOException e) { ... }
Termination vs. resumption  There are two basic models in exception-handling theory.  In  termination  the error is so critical there’s no way to get back to where the exception occurred. Whoever threw the exception decided that there was no way to salvage the situation, and they don’t  want  to come back.  The alternative is called  resumption . It means that the exception handler is expected to do something to rectify the situation, and then the faulting method is retried, presuming success the second time. If you want resumption, it means you still hope to continue execution after the exception is handled.
In resumption a method call that want resumption-like behavior (i.e don’t throw an exception all a method that  fixes the problem.)  Alternatively, place your  try  block inside a  while  loop that keeps reentering the  try  block until the result is satisfactory.  Operating systems that supported resumptive exception handling eventually ended up using termination-like code and skipping resumption.
Exception Hierarchy All exceptions are sub-classes of the build-in class Throwable. Throwable contains two immediate sub-classes: 1) Exception – exceptional conditions that programs should catch The class includes: a) RuntimeException – defined automatically for    user programs to include: division by zero, invalid    array indexing, etc. b) use-defined exception classes 2) Error – exceptions used by Java to indicate errors with the runtime environment; user programs are not supposed to catch them
Hierarchy of Exception Classes
Usage of  try - catch  Statements Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> }
Catching Exceptions: The  try - catch  Statements class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(“Please print me.”); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } System.out.println(“After exception.”); } }
Catching Exceptions: Multiple catch class MultipleCatch { public static void main(String args[]) { try { int den = Integer.parseInt(args[0]); System.out.println(3/den); } catch (ArithmeticException exc) { System.out.println(“Divisor was 0.”); } catch (ArrayIndexOutOfBoundsException exc2) { System.out.println(“Missing argument.”); } System.out.println(“After exception.”); } }
Catching Exceptions: Nested try's class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!&quot;); } } catch (ArrayIndexOutOfBoundsException) { System.out.println(“Need 2 parameters!&quot;); }  }  }
Catching Exceptions: Nested try's with methods class NestedTryDemo2 { static void nestedTry(String args[]) { try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(&quot;Div by zero error!&quot;); }  } public static void main(String args[]){ try { nestedTry(args); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(&quot;Need 2 parameters!&quot;); }  }  }
Throwing Exceptions(throw) So far, we were only catching the exceptions thrown by the Java system. In fact, a user program may throw an exception explicitly: throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or its subclass.
Once an exception is thrown by: throw ThrowableInstance; 1) the flow of control stops immediately 2) the nearest enclosing try statement is inspected if it has a catch statement that matches the type of exception: 1) if one exists, control is transferred to that statement 2) otherwise, the next enclosing try statement is examined 3) if no enclosing try statement has a corresponding catch clause, the default exception handler halts the program and prints the stack
Creating Exceptions Two ways to obtain a Throwable instance: 1) creating one with the new operator All Java built-in exceptions have at least two Constructors:  One without parameters and another with one String  parameter: throw new NullPointerException(&quot;demo&quot;); 2) using a parameter of the catch clause try { … } catch(Throwable e) { … e … }
Example: throw 1 class ThrowDemo { //The method demoproc throws a NullPointerException exception which is immediately caught in the try block and  re-thrown: static void demoproc() { try { throw new NullPointerException(&quot;demo&quot;); } catch(NullPointerException e) { System.out.println(&quot;Caught inside demoproc.&quot;); throw e; } }
Example: throw 2 The main method calls demoproc within the try block which catches and handles the NullPointerException  exception: public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println(&quot;Recaught: &quot; + e); } } }
throws Declaration If a method is capable of causing an exception that it does not handle, it must specify this behavior by the throws clause in its declaration: type name(parameter-list) throws exception-list { … } where exception-list is a comma-separated list of all types of exceptions that a method might throw. All exceptions must be listed except Error and RuntimeException or any of their subclasses, otherwise a compile-time error occurs.
Example: throws 1 The throwOne method throws an exception that it does not catch, nor declares it within the throws clause. class ThrowsDemo { static void throwOne() { System.out.println(&quot;Inside throwOne.&quot;); throw new IllegalAccessException(&quot;demo&quot;); } public static void main(String args[]) { throwOne(); } } Therefore this program does not compile.
Example: throws 2 Corrected program: throwOne lists exception, main catches it: class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println(&quot;Inside throwOne.&quot;); throw new IllegalAccessException(&quot;demo&quot;); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println(&quot;Caught &quot; + e); }  }  }
finally When an exception is thrown: 1) the execution of a method is changed 2) the method may even return prematurely. This may be a problem is many situations. For instance, if a method opens a file on entry and closes on exit; exception handling should not bypass the proper closure of the file. The finally block is used to address this problem.
finally Clause The try/catch statement requires at least one catch or finally clause, although both are optional: try { … } catch(Exception1 ex1) { … } … finally { … } Executed after try/catch whether of not the exception is thrown. Any time a method is to return to a caller from inside the try/catch block via: 1) uncaught exception or 2) explicit return the finally clause is executed just before the method returns.
Example: finally 1 Three methods to exit in various ways. class FinallyDemo { //procA prematurely breaks out of the try by throwing an exception, the finally clause is executed on the way out: static void procA() { try { System.out.println(&quot;inside procA&quot;); throw new RuntimeException(&quot;demo&quot;); } finally { System.out.println(&quot;procA's finally&quot;); } }
Example: finally 2 //  procB’s try statement is exited via a return statement, the finally clause is executed before procB returns: static void procB() { try { System.out.println(&quot;inside procB&quot;); return; } finally { System.out.println(&quot;procB's finally&quot;); } }
Example: finally 3 In procC, the try statement executes normally without error, however the finally clause is still executed: static void procC() { try { System.out.println(&quot;inside procC&quot;); } finally { System.out.println(&quot;procC's finally&quot;); } }
Example: finally 4 Demonstration of the three methods: public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println(&quot;Exception caught&quot;); } procB(); procC(); } }
Java Built-In Exceptions The default java.lang package provides several exception classes, all sub-classing the RuntimeException class. Two sets of build-in exception classes: 1) unchecked exceptions – the compiler does not check if a method handles or throws there exceptions 2) checked exceptions – must be included in the method’s throws clause if the method generates but does not handle them
Unchecked Built-In Exceptions Methods that generate but do not handle those exceptions need not declare them in the throws clause: ArithmeticException ArrayIndexOutOfBoundsException  ArrayStoreException ClassCastException  IllegalStateException IllegalMonitorStateException IllegalArgumentException
StringIndexOutOfBounds UnsupportedOperationException SecurityException  NumberFormatException NullPointerException  NegativeArraySizeException IndexOutOfBoundsException IllegalThreadStateException
Checked Built-In Exceptions Methods that generate but do not handle those exceptions must declare them in the throws clause: NoSuchMethodException NoSuchFieldException  InterruptedException InstantiationException IllegalAccessException CloneNotSupportedException ClassNotFoundException
Creating Own Exception Classes Build-in exception classes handle some generic errors. For application-specific errors define your own exception classes. How? Define a subclass of Exception: class MyException extends Exception { … } MyException need not implement anything – its mere existence in the type system allows to use its objects as exceptions.
Example: Own Exceptions 1 A new exception class is defined, with a private detail variable, a one parameter constructor and an overridden toString method: class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return &quot;MyException[&quot; + detail + &quot;]&quot;; } }
Example: Own Exceptions 2 class ExceptionDemo { The static compute method throws the MyException  exception whenever its a argument is greater than 10: static void compute(int a) throws MyException { System.out.println(&quot;Called compute(&quot; + a + &quot;)&quot;); if (a > 10) throw new MyException(a); System.out.println(&quot;Normal exit&quot;); }
Example: Own Exceptions 3 The main method calls compute with two arguments within a try block that catches the MyException exception: public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println(&quot;Caught &quot; + e); } } }
Differences between multi threading and multitasking Multi-Tasking Two kinds of multi-tasking: 1) process-based multi-tasking 2) thread-based multi-tasking Process-based multi-tasking is about allowing several programs to execute concurrently, e.g. Java compiler and a text editor. Processes are heavyweight tasks: 1) that require their own address space 2) inter-process communication is expensive and limited 3) context-switching from one process to another is expensive   and limited
Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g. a text editor printing and spell-checking text. Threads are lightweight tasks: 1) they share the same address space 2) they cooperatively share the same process 3) inter-thread communication is inexpensive 4) context-switching from one thread to another    is low-cost Java multi-tasking is thread-based.
Reasons for Multi-Threading Multi-threading enables to write efficient programs that make the maximum use of the CPU, keeping the idle time to a minimum. There is plenty of idle time for interactive, networked applications: 1) the transmission rate of data over a network is much    slower than the rate at which the computer can process it 2) local file system resources can be read and written at a much slower rate than can be processed by the CPU 3) of course, user input is much slower than the computer
Thread Lifecycle Thread exist in several states: 1) ready to run 2) running 3) a running thread can be suspended 4) a suspended thread can be resumed 5) a thread can be blocked when waiting for a resource 6) a thread can be terminated Once terminated, a thread cannot be resumed.
Thread Lifecycle Born Blocked Runnable Dead stop() start() stop() Active block on I/O I/O available JVM sleep(500) wake up suspend() resume() wait notify
New state –  After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. Runnable (Ready-to-run) state –  A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. Running state –  A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. Dead state –  A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.  Blocked -  A thread can enter in this state because of waiting the resources that are hold by another thread.
Creating Threads To create a new thread a program will: 1) extend the Thread class, or 2) implement the Runnable interface Thread class encapsulates a thread of execution. The whole Java multithreading environment is based on the Thread class.
Thread Methods Start: a thread by calling start its run method Sleep: suspend a thread for a period of time Run: entry-point for a thread Join: wait for a thread to terminate isAlive: determine if a thread is still running getPriority: obtain a thread’s priority getName: obtain a thread’s name
New Thread: Runnable To create a new thread by implementing the Runnable interface: 1) create a class that implements the run method (inside this method, we define the code that constitutes the new thread): public void run() 2) instantiate a Thread object within that class, a possible constructor is: Thread(Runnable threadOb, String threadName) 3) call the start method on this object (start calls run): void start()
Example: New Thread 1 A class NewThread that implements Runnable: class NewThread implements Runnable { Thread t; //Creating and starting a new thread. Passing this to the // Thread constructor – the new thread will call this // object’s run method: NewThread() { t = new Thread(this, &quot;Demo Thread&quot;); System.out.println(&quot;Child thread: &quot; + t); t.start(); }
Example: New Thread 2 // This is the entry point for the newly created thread – a five-iterations loop //with a half-second pause between the iterations all within try/catch: public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Child Thread: &quot; + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println(&quot;Child interrupted.&quot;); } System.out.println(&quot;Exiting child thread.&quot;); } }
Example: New Thread 3 class ThreadDemo { public static void main(String args[]) { //A new thread is created as an object of // NewThread: new NewThread(); //After calling the NewThread start method, // control returns here.
Example: New Thread 4 //Both threads (new and main) continue concurrently. //Here is the loop for the main thread: try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Main Thread: &quot; + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(&quot;Main thread interrupted.&quot;); } System.out.println(&quot;Main thread exiting.&quot;); } }
New Thread: Extend Thread The second way to create a new thread: 1) create a new class that extends Thread 2) create an instance of that class Thread provides both run and start methods: 1) the extending class must override run 2) it must also call the start method
Example: New Thread 1 The new thread class extends Thread: class NewThread extends Thread { //Create a new thread by calling the Thread’s // constructor and start method: NewThread() { super(&quot;Demo Thread&quot;); System.out.println(&quot;Child thread: &quot; + this); start(); }
Example: New Thread 2 NewThread overrides the Thread’s run method: public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Child Thread: &quot; + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println(&quot;Child interrupted.&quot;); } System.out.println(&quot;Exiting child thread.&quot;); } }
Example: New Thread 3 class ExtendThread { public static void main(String args[]) { //After a new thread is created: new NewThread(); //the new and main threads continue //concurrently…
Example: New Thread 4 //This is the loop of the main thread: try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Main Thread: &quot; + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(&quot;Main thread interrupted.&quot;); } System.out.println(&quot;Main thread exiting.&quot;); } }
Threads: Synchronization Multi-threading introduces asynchronous behavior to a program. How to ensure synchronous behavior when we need it? For instance, how to prevent two threads from simultaneously writing and reading the same object? Java implementation of monitors: 1) classes can define so-called synchronized methods 2) each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called 3) once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object
Thread Synchronization Language keyword:  synchronized Takes out a  monitor lock  on an object Exclusive lock for that thread If lock is currently unavailable, thread will block
Thread Synchronization Protects access to code, not to data Make data members private Synchronize accessor methods Puts a “force field” around the locked object so no other threads can enter Actually, it only blocks access to other synchronizing threads
Daemon Threads  Any Java thread can be a  daemon  thread.  Daemon threads are service providers for other threads running in the same process as the daemon thread.  The run() method for a daemon thread is typically an infinite loop that waits for a service request. When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.  To specify that a thread is a daemon thread, call the setDaemon method with the argument true. To determine if a thread is a daemon thread, use the accessor method isDaemon.
Thread Groups Every Java thread is a member of a  thread group .  Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call.  Java thread groups are implemented by the “ThreadGroup” class in the java.lang package.  The runtime system puts a thread into a thread group during thread construction.  When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group. The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created
The ThreadGroup Class  The “ThreadGroup” class manages groups of threads for Java applications.  A ThreadGroup can contain any number of threads.  The threads in a group are generally related in some way, such as who created them, what function they perform, or when they should be started and stopped.  ThreadGroups can contain not only threads but also other ThreadGroups.  The top-most thread group in a Java application is the thread group named main.  You can create threads and thread groups in the main group.  You can also create threads and thread groups in subgroups of main.
Creating a Thread Explicitly in a Group A thread is a permanent member of whatever thread group it joins when its created--you cannot move a thread to a new group after the thread has been created. Thus, if you wish to put your new thread in a thread group other than the default, you must specify the thread group explicitly when you create the thread. The Thread class has three constructors that let you set a new thread's group: public Thread(ThreadGroup  group , Runnable  target ) public  Thread(ThreadGroup  group , String  name ) public Thread(ThreadGroup  group , Runnable  target , String  name ) Each of these constructors creates a new thread, initializes it based on the Runnable and String parameters, and makes the new thread a member of the specified group.  For example: ThreadGroup myThreadGroup = new ThreadGroup(&quot;My Group of Threads&quot;);  Thread myThread = new Thread(myThreadGroup, &quot;a thread for my group&quot;);
Ad

More Related Content

What's hot (20)

Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
upen.rockin
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
Deepak Tathe
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
parveen837153
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
Methods in java
Methods in javaMethods in java
Methods in java
chauhankapil
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
Servlets
ServletsServlets
Servlets
Rajkiran Mummadi
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Exception Handling In Python | Exceptions In Python | Python Programming Tuto...
Edureka!
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 
Reflection in java
Reflection in javaReflection in java
Reflection in java
upen.rockin
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
Deepak Tathe
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
parveen837153
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
CPD INDIA
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
Viji B
 
Command line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorialCommand line-arguments-in-java-tutorial
Command line-arguments-in-java-tutorial
Kuntal Bhowmick
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
Maulik Borsaniya
 
Lecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptxLecture_7-Encapsulation in Java.pptx
Lecture_7-Encapsulation in Java.pptx
ShahinAhmed49
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 

Viewers also liked (20)

Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
arnold 7490
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
arnold 7490
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
arnold 7490
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Unit3 C
Unit3 C Unit3 C
Unit3 C
arnold 7490
 
Exception
ExceptionException
Exception
Марія Русин
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
arnold 7490
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
rajveer_Pannu
 
New operator and methods.15
New operator and methods.15New operator and methods.15
New operator and methods.15
myrajendra
 
Chapter 2.datatypes and operators
Chapter 2.datatypes and operatorsChapter 2.datatypes and operators
Chapter 2.datatypes and operators
Jasleen Kaur (Chandigarh University)
 
Operators
OperatorsOperators
Operators
moniammu
 
Console Io Operations
Console Io OperationsConsole Io Operations
Console Io Operations
archikabhatia
 
Template at c++
Template at c++Template at c++
Template at c++
Lusain Kim
 
Managing console
Managing consoleManaging console
Managing console
Shiva Saxena
 
constructor & destructor in cpp
constructor & destructor in cppconstructor & destructor in cpp
constructor & destructor in cpp
gourav kottawar
 
Mca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structureMca ii dfs u-1 introduction to data structure
Mca ii dfs u-1 introduction to data structure
Rai University
 
C++ Template
C++ TemplateC++ Template
C++ Template
Saket Pathak
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
Mayank Bhatt
 
Ad

Similar to Unit 5 Java (20)

Unit-5.ppt JAVA VTU PPT PRESENTEATION BY
Unit-5.ppt JAVA VTU PPT PRESENTEATION BYUnit-5.ppt JAVA VTU PPT PRESENTEATION BY
Unit-5.ppt JAVA VTU PPT PRESENTEATION BY
dsajadhav369
 
Exception Handling.ppt
 Exception Handling.ppt Exception Handling.ppt
Exception Handling.ppt
Faisaliqbal203156
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptions
parthu310
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
Arjun Shanka
 
Exception and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .pptException and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .ppt
JyothiAmpally
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exceptions
ExceptionsExceptions
Exceptions
motthu18
 
Java Exceptions
Java ExceptionsJava Exceptions
Java Exceptions
jalinder123
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
DrRajeshreeKhande
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programmingException‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Unit-5.ppt JAVA VTU PPT PRESENTEATION BY
Unit-5.ppt JAVA VTU PPT PRESENTEATION BYUnit-5.ppt JAVA VTU PPT PRESENTEATION BY
Unit-5.ppt JAVA VTU PPT PRESENTEATION BY
dsajadhav369
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptions
parthu310
 
Exception and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .pptException and ErrorHandling in Java .ppt
Exception and ErrorHandling in Java .ppt
JyothiAmpally
 
Exception handling
Exception handlingException handling
Exception handling
zindadili
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptxModule 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
mcaajiet25
 
Exceptions
ExceptionsExceptions
Exceptions
motthu18
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programmingException‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Ad

More from arnold 7490 (20)

Les14
Les14Les14
Les14
arnold 7490
 
Les13
Les13Les13
Les13
arnold 7490
 
Les11
Les11Les11
Les11
arnold 7490
 
Les10
Les10Les10
Les10
arnold 7490
 
Les09
Les09Les09
Les09
arnold 7490
 
Les03
Les03Les03
Les03
arnold 7490
 
Les02
Les02Les02
Les02
arnold 7490
 
Les01
Les01Les01
Les01
arnold 7490
 
Les12
Les12Les12
Les12
arnold 7490
 
Unit 2 Java
Unit 2 JavaUnit 2 Java
Unit 2 Java
arnold 7490
 
Unit 7 Java
Unit 7 JavaUnit 7 Java
Unit 7 Java
arnold 7490
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
arnold 7490
 
Unit5 C
Unit5 C Unit5 C
Unit5 C
arnold 7490
 
Unit4 C
Unit4 C Unit4 C
Unit4 C
arnold 7490
 
Unit2 C
Unit2 C Unit2 C
Unit2 C
arnold 7490
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
arnold 7490
 

Recently uploaded (20)

Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
Agentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community MeetupAgentic Automation - Delhi UiPath Community Meetup
Agentic Automation - Delhi UiPath Community Meetup
Manoj Batra (1600 + Connections)
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptxSmart Investments Leveraging Agentic AI for Real Estate Success.pptx
Smart Investments Leveraging Agentic AI for Real Estate Success.pptx
Seasia Infotech
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Developing System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptxDeveloping System Infrastructure Design Plan.pptx
Developing System Infrastructure Design Plan.pptx
wondimagegndesta
 
IT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information TechnologyIT488 Wireless Sensor Networks_Information Technology
IT488 Wireless Sensor Networks_Information Technology
SHEHABALYAMANI
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
GDG Cloud Southlake #42: Suresh Mathew: Autonomous Resource Optimization: How...
James Anderson
 
Top-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptxTop-AI-Based-Tools-for-Game-Developers (1).pptx
Top-AI-Based-Tools-for-Game-Developers (1).pptx
BR Softech
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Slack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teamsSlack like a pro: strategies for 10x engineering teams
Slack like a pro: strategies for 10x engineering teams
Nacho Cougil
 
Viam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdfViam product demo_ Deploying and scaling AI with hardware.pdf
Viam product demo_ Deploying and scaling AI with hardware.pdf
camilalamoratta
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
On-Device or Remote? On the Energy Efficiency of Fetching LLM-Generated Conte...
Ivano Malavolta
 
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
RTP Over QUIC: An Interesting Opportunity Or Wasted Time?
Lorenzo Miniero
 
AsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API DesignAsyncAPI v3 : Streamlining Event-Driven API Design
AsyncAPI v3 : Streamlining Event-Driven API Design
leonid54
 
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier VroomAI x Accessibility UXPA by Stew Smith and Olivier Vroom
AI x Accessibility UXPA by Stew Smith and Olivier Vroom
UXPA Boston
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 

Unit 5 Java

  • 1. OBJECT ORIENTED PROGRAMMING
  • 2. INDEX UNIT 4 PPT SLIDES S.NO. TOPIC LECTURE NO. PPTSLIDES Concepts of exception handling L1 L1.1TO L1.5 Benefits of exception handling L2 L2.1 TO L2.14 Termination or resumptive models Exception hierarchy, usage of try, catch L3 L3.1 TO L3.7 throw, throws and finally L 4 L4.1 TO L4.14 built in exceptions L5 L5.1 TO 5.4 creating own exception sub classes L6 L6.1 TO 6.4 Differences between multi threading and multitasking L7 L7.1 TO 7.6 thread life cycle 8 creating threads, synchronizing threads L8 L 8.1 TO 8.15 9 daemon threads, thread groups. L9 L 9.1 TO 9.4
  • 3. Concepts of exception handling Exceptions Exception is an abnormal condition that arises when executing a program. In the languages that do not support exception handling, errors must be checked and handled manually, usually through the use of error codes. In contrast, Java: 1) provides syntactic mechanisms to signal, detect and handle errors 2) ensures a clean separation between the code executed in the absence of errors and the code to handle various kinds of errors 3) brings run-time error management into object-oriented programming
  • 4. Exception Handling An exception is an object that describes an exceptional condition (error) that has occurred when executing a program. Exception handling involves the following: 1) when an error occurs, an object (exception) representing this error is created and thrown in the method that caused it 2) that method may choose to handle the exception itself or pass it on 3) either way, at some point, the exception is caught and processed
  • 5. Exception Sources Exceptions can be: 1) generated by the Java run-time system Fundamental errors that violate the rules of the Java language or the constraints of the Java execution environment. 2) manually generated by programmer’s code Such exceptions are typically used to report some error conditions to the caller of a method.
  • 6. Exception Constructs Five constructs are used in exception handling: 1) try – a block surrounding program statements to monitor for exceptions 2) catch – together with try, catches specific kinds of exceptions and handles them in some way 3) finally – specifies any code that absolutely must be executed whether or not an exception occurs 4) throw – used to throw a specific exception from the program 5) throws – specifies which exceptions a given method can throw
  • 7. Exception-Handling Block General form: try { … } catch(Exception1 ex1) { … } catch(Exception2 ex2) { … } … finally { … } where: 1) try { … } is the block of code to monitor for exceptions 2) catch(Exception ex) { … } is exception handler for the exception Exception 3) finally { … } is the block of code to execute before the try block ends
  • 8. Benefits of exception handling Separating Error-Handling code from “regular” business logic code Propagating errors up the call stack Grouping and differentiating error types
  • 9. Separating Error Handling Code from Regular Code In traditional programming, error detection, reporting, and handling often lead to confusing code Consider pseudocode method here that reads an entire file into memory readFile { open the file; determine its size; allocate that much memory; read the file into memory; close the file; }
  • 10. Traditional Programming: No separation of error handling code ● In traditional programming, To handle such cases, the readFile function must have more code to do error detection, reporting, and handling. errorCodeType readFile { initialize errorCode = 0; open the file; if (theFileIsOpen) { determine the length of the file; if (gotTheFileLength) { allocate that much memory; if (gotEnoughMemory) { read the file into memory; if (readFailed) { errorCode = -1; } }
  • 11. else { errorCode = -2; } } else { errorCode = -3; } close the file; if (theFileDidntClose && errorCode == 0) { errorCode = -4; } else { errorCode = errorCode and -4; } } else { errorCode = -5; } return errorCode; }
  • 12. Separating Error Handling Code from Regular Code (in Java) Exceptions enable you to write the main flow of your code and to deal with the exceptional cases elsewhere readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; }
  • 13. catch (sizeDeterminationFailed) { doSomething; }catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } } Note that exceptions don't spare you the effort of doing the work of detecting, reporting, and handling errors, but they do help you organize the work more effectively.
  • 14. Propagating Errors Up the Call Stack Suppose that the readFile method is the fourth method in a series of nested method calls made by the main program: method1 calls method2 , which calls method3 , which finally calls readFile Suppose also that method1 is the only method interested in the errors that might occur within readFile . method1 { call method2; } method2 { call method3; } method3 { call readFile; }
  • 15. Traditional Way of Propagating Errors method1 { errorCodeType error; error = call method2; if (error) doErrorProcessing; else proceed; } errorCodeType method2 { errorCodeType error; error = call method3; if (error) return error; else proceed; } errorCodeType method3 { errorCodeType error; error = call readFile; if (error) return error; else proceed; } Traditional error notification Techniques force method2 and method3 to propagate the error codes returned by readFile up the call stack until the error codes finally reach method1— the only method that is interested in them.
  • 16. Using Java Exception Handling method1 { try { call method2; } catch (exception e) { doErrorProcessing; } } method2 throws exception { call method3; } method3 throws exception { call readFile; } Any checked exceptions that can be thrown within a method must be specified in its throws clause.
  • 17. Grouping and Differentiating Error Types Because all exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy An example of a group of related exception classes in the Java platform are those defined in java.io.IOException and its descendants IOException is the most general and represents any type of error that can occur when performing I/O Its descendants represent more specific errors. For example, FileNotFoundException means that a file could not be located on disk.
  • 18. A method can write specific handlers that can handle a very specific exception The FileNotFoundException class has no descendants, so the following handler can handle only one type of exception. catch (FileNotFoundException e) { ... }
  • 19. A method can catch an exception based on its group or general type by specifying any of the exception's super classes in the catch statement. For example, to catch all I/O exceptions, regardless of their specific type, an exception handler specifies an IOException argument. // Catch all I/O exceptions, including // FileNotFoundException, EOFException, and so on. catch (IOException e) { ... }
  • 20. Termination vs. resumption There are two basic models in exception-handling theory. In termination the error is so critical there’s no way to get back to where the exception occurred. Whoever threw the exception decided that there was no way to salvage the situation, and they don’t want to come back. The alternative is called resumption . It means that the exception handler is expected to do something to rectify the situation, and then the faulting method is retried, presuming success the second time. If you want resumption, it means you still hope to continue execution after the exception is handled.
  • 21. In resumption a method call that want resumption-like behavior (i.e don’t throw an exception all a method that fixes the problem.) Alternatively, place your try block inside a while loop that keeps reentering the try block until the result is satisfactory. Operating systems that supported resumptive exception handling eventually ended up using termination-like code and skipping resumption.
  • 22. Exception Hierarchy All exceptions are sub-classes of the build-in class Throwable. Throwable contains two immediate sub-classes: 1) Exception – exceptional conditions that programs should catch The class includes: a) RuntimeException – defined automatically for user programs to include: division by zero, invalid array indexing, etc. b) use-defined exception classes 2) Error – exceptions used by Java to indicate errors with the runtime environment; user programs are not supposed to catch them
  • 24. Usage of try - catch Statements Syntax: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> }
  • 25. Catching Exceptions: The try - catch Statements class DivByZero { public static void main(String args[]) { try { System.out.println(3/0); System.out.println(“Please print me.”); } catch (ArithmeticException exc) { //Division by zero is an ArithmeticException System.out.println(exc); } System.out.println(“After exception.”); } }
  • 26. Catching Exceptions: Multiple catch class MultipleCatch { public static void main(String args[]) { try { int den = Integer.parseInt(args[0]); System.out.println(3/den); } catch (ArithmeticException exc) { System.out.println(“Divisor was 0.”); } catch (ArrayIndexOutOfBoundsException exc2) { System.out.println(“Missing argument.”); } System.out.println(“After exception.”); } }
  • 27. Catching Exceptions: Nested try's class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!&quot;); } } catch (ArrayIndexOutOfBoundsException) { System.out.println(“Need 2 parameters!&quot;); } } }
  • 28. Catching Exceptions: Nested try's with methods class NestedTryDemo2 { static void nestedTry(String args[]) { try { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(&quot;Div by zero error!&quot;); } } public static void main(String args[]){ try { nestedTry(args); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(&quot;Need 2 parameters!&quot;); } } }
  • 29. Throwing Exceptions(throw) So far, we were only catching the exceptions thrown by the Java system. In fact, a user program may throw an exception explicitly: throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or its subclass.
  • 30. Once an exception is thrown by: throw ThrowableInstance; 1) the flow of control stops immediately 2) the nearest enclosing try statement is inspected if it has a catch statement that matches the type of exception: 1) if one exists, control is transferred to that statement 2) otherwise, the next enclosing try statement is examined 3) if no enclosing try statement has a corresponding catch clause, the default exception handler halts the program and prints the stack
  • 31. Creating Exceptions Two ways to obtain a Throwable instance: 1) creating one with the new operator All Java built-in exceptions have at least two Constructors: One without parameters and another with one String parameter: throw new NullPointerException(&quot;demo&quot;); 2) using a parameter of the catch clause try { … } catch(Throwable e) { … e … }
  • 32. Example: throw 1 class ThrowDemo { //The method demoproc throws a NullPointerException exception which is immediately caught in the try block and re-thrown: static void demoproc() { try { throw new NullPointerException(&quot;demo&quot;); } catch(NullPointerException e) { System.out.println(&quot;Caught inside demoproc.&quot;); throw e; } }
  • 33. Example: throw 2 The main method calls demoproc within the try block which catches and handles the NullPointerException exception: public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println(&quot;Recaught: &quot; + e); } } }
  • 34. throws Declaration If a method is capable of causing an exception that it does not handle, it must specify this behavior by the throws clause in its declaration: type name(parameter-list) throws exception-list { … } where exception-list is a comma-separated list of all types of exceptions that a method might throw. All exceptions must be listed except Error and RuntimeException or any of their subclasses, otherwise a compile-time error occurs.
  • 35. Example: throws 1 The throwOne method throws an exception that it does not catch, nor declares it within the throws clause. class ThrowsDemo { static void throwOne() { System.out.println(&quot;Inside throwOne.&quot;); throw new IllegalAccessException(&quot;demo&quot;); } public static void main(String args[]) { throwOne(); } } Therefore this program does not compile.
  • 36. Example: throws 2 Corrected program: throwOne lists exception, main catches it: class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println(&quot;Inside throwOne.&quot;); throw new IllegalAccessException(&quot;demo&quot;); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println(&quot;Caught &quot; + e); } } }
  • 37. finally When an exception is thrown: 1) the execution of a method is changed 2) the method may even return prematurely. This may be a problem is many situations. For instance, if a method opens a file on entry and closes on exit; exception handling should not bypass the proper closure of the file. The finally block is used to address this problem.
  • 38. finally Clause The try/catch statement requires at least one catch or finally clause, although both are optional: try { … } catch(Exception1 ex1) { … } … finally { … } Executed after try/catch whether of not the exception is thrown. Any time a method is to return to a caller from inside the try/catch block via: 1) uncaught exception or 2) explicit return the finally clause is executed just before the method returns.
  • 39. Example: finally 1 Three methods to exit in various ways. class FinallyDemo { //procA prematurely breaks out of the try by throwing an exception, the finally clause is executed on the way out: static void procA() { try { System.out.println(&quot;inside procA&quot;); throw new RuntimeException(&quot;demo&quot;); } finally { System.out.println(&quot;procA's finally&quot;); } }
  • 40. Example: finally 2 // procB’s try statement is exited via a return statement, the finally clause is executed before procB returns: static void procB() { try { System.out.println(&quot;inside procB&quot;); return; } finally { System.out.println(&quot;procB's finally&quot;); } }
  • 41. Example: finally 3 In procC, the try statement executes normally without error, however the finally clause is still executed: static void procC() { try { System.out.println(&quot;inside procC&quot;); } finally { System.out.println(&quot;procC's finally&quot;); } }
  • 42. Example: finally 4 Demonstration of the three methods: public static void main(String args[]) { try { procA(); } catch (Exception e) { System.out.println(&quot;Exception caught&quot;); } procB(); procC(); } }
  • 43. Java Built-In Exceptions The default java.lang package provides several exception classes, all sub-classing the RuntimeException class. Two sets of build-in exception classes: 1) unchecked exceptions – the compiler does not check if a method handles or throws there exceptions 2) checked exceptions – must be included in the method’s throws clause if the method generates but does not handle them
  • 44. Unchecked Built-In Exceptions Methods that generate but do not handle those exceptions need not declare them in the throws clause: ArithmeticException ArrayIndexOutOfBoundsException ArrayStoreException ClassCastException IllegalStateException IllegalMonitorStateException IllegalArgumentException
  • 45. StringIndexOutOfBounds UnsupportedOperationException SecurityException NumberFormatException NullPointerException NegativeArraySizeException IndexOutOfBoundsException IllegalThreadStateException
  • 46. Checked Built-In Exceptions Methods that generate but do not handle those exceptions must declare them in the throws clause: NoSuchMethodException NoSuchFieldException InterruptedException InstantiationException IllegalAccessException CloneNotSupportedException ClassNotFoundException
  • 47. Creating Own Exception Classes Build-in exception classes handle some generic errors. For application-specific errors define your own exception classes. How? Define a subclass of Exception: class MyException extends Exception { … } MyException need not implement anything – its mere existence in the type system allows to use its objects as exceptions.
  • 48. Example: Own Exceptions 1 A new exception class is defined, with a private detail variable, a one parameter constructor and an overridden toString method: class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return &quot;MyException[&quot; + detail + &quot;]&quot;; } }
  • 49. Example: Own Exceptions 2 class ExceptionDemo { The static compute method throws the MyException exception whenever its a argument is greater than 10: static void compute(int a) throws MyException { System.out.println(&quot;Called compute(&quot; + a + &quot;)&quot;); if (a > 10) throw new MyException(a); System.out.println(&quot;Normal exit&quot;); }
  • 50. Example: Own Exceptions 3 The main method calls compute with two arguments within a try block that catches the MyException exception: public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println(&quot;Caught &quot; + e); } } }
  • 51. Differences between multi threading and multitasking Multi-Tasking Two kinds of multi-tasking: 1) process-based multi-tasking 2) thread-based multi-tasking Process-based multi-tasking is about allowing several programs to execute concurrently, e.g. Java compiler and a text editor. Processes are heavyweight tasks: 1) that require their own address space 2) inter-process communication is expensive and limited 3) context-switching from one process to another is expensive and limited
  • 52. Thread-Based Multi-Tasking Thread-based multi-tasking is about a single program executing concurrently several tasks e.g. a text editor printing and spell-checking text. Threads are lightweight tasks: 1) they share the same address space 2) they cooperatively share the same process 3) inter-thread communication is inexpensive 4) context-switching from one thread to another is low-cost Java multi-tasking is thread-based.
  • 53. Reasons for Multi-Threading Multi-threading enables to write efficient programs that make the maximum use of the CPU, keeping the idle time to a minimum. There is plenty of idle time for interactive, networked applications: 1) the transmission rate of data over a network is much slower than the rate at which the computer can process it 2) local file system resources can be read and written at a much slower rate than can be processed by the CPU 3) of course, user input is much slower than the computer
  • 54. Thread Lifecycle Thread exist in several states: 1) ready to run 2) running 3) a running thread can be suspended 4) a suspended thread can be resumed 5) a thread can be blocked when waiting for a resource 6) a thread can be terminated Once terminated, a thread cannot be resumed.
  • 55. Thread Lifecycle Born Blocked Runnable Dead stop() start() stop() Active block on I/O I/O available JVM sleep(500) wake up suspend() resume() wait notify
  • 56. New state – After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. Runnable (Ready-to-run) state – A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again. Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.
  • 57. Creating Threads To create a new thread a program will: 1) extend the Thread class, or 2) implement the Runnable interface Thread class encapsulates a thread of execution. The whole Java multithreading environment is based on the Thread class.
  • 58. Thread Methods Start: a thread by calling start its run method Sleep: suspend a thread for a period of time Run: entry-point for a thread Join: wait for a thread to terminate isAlive: determine if a thread is still running getPriority: obtain a thread’s priority getName: obtain a thread’s name
  • 59. New Thread: Runnable To create a new thread by implementing the Runnable interface: 1) create a class that implements the run method (inside this method, we define the code that constitutes the new thread): public void run() 2) instantiate a Thread object within that class, a possible constructor is: Thread(Runnable threadOb, String threadName) 3) call the start method on this object (start calls run): void start()
  • 60. Example: New Thread 1 A class NewThread that implements Runnable: class NewThread implements Runnable { Thread t; //Creating and starting a new thread. Passing this to the // Thread constructor – the new thread will call this // object’s run method: NewThread() { t = new Thread(this, &quot;Demo Thread&quot;); System.out.println(&quot;Child thread: &quot; + t); t.start(); }
  • 61. Example: New Thread 2 // This is the entry point for the newly created thread – a five-iterations loop //with a half-second pause between the iterations all within try/catch: public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Child Thread: &quot; + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println(&quot;Child interrupted.&quot;); } System.out.println(&quot;Exiting child thread.&quot;); } }
  • 62. Example: New Thread 3 class ThreadDemo { public static void main(String args[]) { //A new thread is created as an object of // NewThread: new NewThread(); //After calling the NewThread start method, // control returns here.
  • 63. Example: New Thread 4 //Both threads (new and main) continue concurrently. //Here is the loop for the main thread: try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Main Thread: &quot; + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(&quot;Main thread interrupted.&quot;); } System.out.println(&quot;Main thread exiting.&quot;); } }
  • 64. New Thread: Extend Thread The second way to create a new thread: 1) create a new class that extends Thread 2) create an instance of that class Thread provides both run and start methods: 1) the extending class must override run 2) it must also call the start method
  • 65. Example: New Thread 1 The new thread class extends Thread: class NewThread extends Thread { //Create a new thread by calling the Thread’s // constructor and start method: NewThread() { super(&quot;Demo Thread&quot;); System.out.println(&quot;Child thread: &quot; + this); start(); }
  • 66. Example: New Thread 2 NewThread overrides the Thread’s run method: public void run() { try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Child Thread: &quot; + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println(&quot;Child interrupted.&quot;); } System.out.println(&quot;Exiting child thread.&quot;); } }
  • 67. Example: New Thread 3 class ExtendThread { public static void main(String args[]) { //After a new thread is created: new NewThread(); //the new and main threads continue //concurrently…
  • 68. Example: New Thread 4 //This is the loop of the main thread: try { for (int i = 5; i > 0; i--) { System.out.println(&quot;Main Thread: &quot; + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(&quot;Main thread interrupted.&quot;); } System.out.println(&quot;Main thread exiting.&quot;); } }
  • 69. Threads: Synchronization Multi-threading introduces asynchronous behavior to a program. How to ensure synchronous behavior when we need it? For instance, how to prevent two threads from simultaneously writing and reading the same object? Java implementation of monitors: 1) classes can define so-called synchronized methods 2) each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called 3) once a thread is inside a synchronized method, no other thread can call any other synchronized method on the same object
  • 70. Thread Synchronization Language keyword: synchronized Takes out a monitor lock on an object Exclusive lock for that thread If lock is currently unavailable, thread will block
  • 71. Thread Synchronization Protects access to code, not to data Make data members private Synchronize accessor methods Puts a “force field” around the locked object so no other threads can enter Actually, it only blocks access to other synchronizing threads
  • 72. Daemon Threads Any Java thread can be a daemon thread. Daemon threads are service providers for other threads running in the same process as the daemon thread. The run() method for a daemon thread is typically an infinite loop that waits for a service request. When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service. To specify that a thread is a daemon thread, call the setDaemon method with the argument true. To determine if a thread is a daemon thread, use the accessor method isDaemon.
  • 73. Thread Groups Every Java thread is a member of a thread group . Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the “ThreadGroup” class in the java.lang package. The runtime system puts a thread into a thread group during thread construction. When you create a thread, you can either allow the runtime system to put the new thread in some reasonable default group or you can explicitly set the new thread's group. The thread is a permanent member of whatever thread group it joins upon its creation--you cannot move a thread to a new group after the thread has been created
  • 74. The ThreadGroup Class The “ThreadGroup” class manages groups of threads for Java applications. A ThreadGroup can contain any number of threads. The threads in a group are generally related in some way, such as who created them, what function they perform, or when they should be started and stopped. ThreadGroups can contain not only threads but also other ThreadGroups. The top-most thread group in a Java application is the thread group named main. You can create threads and thread groups in the main group. You can also create threads and thread groups in subgroups of main.
  • 75. Creating a Thread Explicitly in a Group A thread is a permanent member of whatever thread group it joins when its created--you cannot move a thread to a new group after the thread has been created. Thus, if you wish to put your new thread in a thread group other than the default, you must specify the thread group explicitly when you create the thread. The Thread class has three constructors that let you set a new thread's group: public Thread(ThreadGroup group , Runnable target ) public Thread(ThreadGroup group , String name ) public Thread(ThreadGroup group , Runnable target , String name ) Each of these constructors creates a new thread, initializes it based on the Runnable and String parameters, and makes the new thread a member of the specified group. For example: ThreadGroup myThreadGroup = new ThreadGroup(&quot;My Group of Threads&quot;); Thread myThread = new Thread(myThreadGroup, &quot;a thread for my group&quot;);
  翻译: