SlideShare a Scribd company logo
1 of 35
Lecture-20
Instructor Name:
Object Oriented Programming
Today’s Lecture
 Defensive Programming
 Exception Handling
2
Defensive Programming
What is Defensive Programming?
 In a Client – Server Interaction where a server object only perform
activities on client request.
 While writing server class, a programmer can adopt two possible
ways
1. They can assume that client objects will know what they are doing and
will request services only in a sensible and well-defined way.
2. They can assume that server objects will operate in an essentially
problematic environment in which all possible steps must be taken to
prevent client objects from using them incorrectly.
 Extreme views
 Practically, scenario lies some where in between
 A third possibility, of course, is an intentionally hostile client who is trying
to break or find a weakness in the server. 3
Defensive Programming
Questions to Discuss
 Different views - a useful base to discuss questions such as:
 How much checking should a server’s methods perform on client
requests?
 How should a server report errors to its clients?
 How can a client anticipate failure of a request to a server?
 How should a client deal with failure of a request?
 So far we have written all the classes with implicit trust that client will use
these classes appropriately
4
Defensive Programming
Parameter Checking
 A server object is most vulnerable when its constructor and methods
receive external values through their parameters.
 The values passed to a constructor are used to set up an object’s initial
state, while the values passed to a method will be used to influence
the overall effect of the method call and may change the state of the
object and a result the method returns.
 It is vital that a server object knows whether it can trust parameter
values to be valid or whether it needs to check their validity for itself.
5
Defensive Programming
Server Error Reporting
 Having protected a server object from performing an illegal operation
through bad parameter values is all that the server writer needs to do.
 Ideally we should like to avoid such error situations from arising in
the first place.
 Furthermore, it is often the case that incorrect parameter values are
the result of some form of programming error in the client that
supplied them.
 Therefore, rather than simply programming around the problem in
the server and leaving it at that, it is good practice for the server to
make some effort to indicate that a problem has arisen, either to the
client itself or to a human user or programmer.
 Here we see three different nature of users
6
Defensive Programming
Notifying User
 Print an error message
 Two Problems with this Approach
1. They assume that the application is being used by a human user who will
see the error message. There are many applications that run completely
independently of a human user. An error message, or an error window,
will go completely unnoticed.
2. Even where there is a human user to see the error message, it will be rare
for that user to be in a position to do something about the problem.
 Programs that print inappropriate error messages are more likely to annoy
their users rather than achieve a useful outcome.
 Except in a very limited set of circumstances, notifying the user is not a
general solution to the problem of error reporting.
7
Defensive Programming
Notifying Client Object
 There are two main ways to notify client object
1. A server can use a non-void return type (e.g boolean) of a method to
return a value that indicates either success or failure of the method call.
2. A server can throw an exception if something goes wrong.
8
Exceptions
What is an Exception?
 An Exception is an event, which occurs during the execution of a program,
that disrupts the normal flow of the program's Instructions.
 An exception can occur for many different reasons, below given are some
scenarios where exception occurs.
 A user has entered invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of communications or
the JVM has run out of memory.
 Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
9
Exceptions
Three Categories of Exception
 Checked Exception : A checked exception is an exception that occurs at the
compile time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored at the time of compilation, the
Programmer should take care of (handle) these exceptions.
 Unchecked Exception : An Unchecked exception is an exception that occurs at
the time of execution, these are also called as Runtime Exceptions, these
include programming bugs, such as logic errors or improper use of an API.
runtime exceptions are ignored at the time of compilation.
 Error: These are not exceptions at all, but problems that arise beyond the
control of the user or the programmer. Errors are typically ignored in your
code because you can rarely do anything about an error. For example, if a
stack overflow occurs, an error will arise. They are also ignored at the time of
compilation.
10
Exception Handling
What is Exception Handling?
 The process of converting system error messages into user friendly error
message is known as Exception handling.
 This is one of the powerful feature of Java to handle run time error and
maintain normal flow of java application.
11
Exception Hierarchy
12
Exception Handling
Methods with Description
 public String getMessage()
Returns a detailed message about the exception that has occurred. This
message is initialized in the Throwable constructor
 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
 public String toString()
Returns the name of the class concatenated with the result of getMessage()
 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the
error output stream.
There are more method, Google for better understanding of Exception
13
Exception Throwing
Throwing an Exception
 Throwing an exception is the most effective way a server object has of
indicating that it is unable to fulfill a call on one of its methods.
 One of the major advantages this has over using a special return value is that
it is (almost) impossible for a client to ignore the fact that an exception has
been thrown and carry on regardless.
 Failure by the client to handle an exception will result in the application
terminating immediately.
 In addition, the exception mechanism is independent of the return value of a
method, so it can be used for all methods, irrespective of the return type
 An Exception is thrown using throw statement. 14
Exception Throwing
Throwing an Unchecked Exception Example
 Here getDetails method is throwing an exception to indicate that passing a
nullvalue for the key does not make sense because it is not a valid key.
publicContactDetails getDetails(String key)
{
if(key == null){
throw new IllegalArgumentException(
"null key in getDetails");
}
return book.get(key);
}
15
Exception Throwing
Throwing Exception Principles
 Exception Mechanism is independent of the return value of method, so it can
be used for all methods, irrespective of all return types
 The place where an error is discovered will be distinct from where recovery is
attempted
 Discovery will be in server’s method
 Recovery will be in the client
 If recovery were possible at the point of discovery then there would be no
point in throwing an exception
16
Exception Throwing
Throwing an Exception
 Two stages involve in throwing exception
1. First, an exception object is created using the new keyword
2. the exception object is thrown using the throw keyword
 When an exception object is created, a diagnostic string may be passed to its
constructor.
 This string is later available to the receiver of the exception via the exception
object’s getMessage and toString methods.
 The string is also shown to the user if the exception is not handled and leads
to the termination of the program.
 The exception type we have used here, IllegalArgumentException, is
defined in the java.lang package and is regularly used to indicate that an
inappropriate actual parameter value has been passed to a method or
constructor.
17
Exception Throwing
Checked vs Unchecked Exceptions
 Checked exceptions are intended for cases where the client should expect that
an operation could fail (for example, if it tries to write to a disk, it should
anticipate that the disk could be full).
 In such cases, the client will be forced to check whether the operation was
successful.
 Unchecked exceptions are intended for cases that should never fail in normal
operation—they usually indicate a program error.
 For instance, a programmer would never knowingly try to get an item from a
position in a list that does not exist, so when they do, it elicits an unchecked
exception.
18
Exception Throwing
The Effect of an Exception
 Two Effects
1. the effect in the method where the problem is discovered and the
exception is thrown
2. the effect in the caller of the problem method
 When an exception is thrown, the execution of the current method finishes
immediately; it does not continue to the end of the method body
 Consider the following contrived call to getDetails:
String phone = details.getPhone();
 The execution of these statements will be left incomplete
19
Exception Throwing
Preventing Object from Creation
 An important use for exceptions is to prevent objects from being created if
they cannot be placed in a valid initial state
 This will usually be the result of inappropriate parameter values being
passed to a constructor.
 The process of throwing an exception from a constructor is exactly the same
as throwing one from a method
 An exception thrown from a constructor has the same effect on the client as
an exception thrown from a method.
20
Exception Handling
Checked Exceptions – the throws clause
 The first requirement of the compiler is that a method throwing a checked
exception must declare that it does so in a throws clause added to the
method’s header.
public void saveToFile(String destinationFile)
throws IOException
 It is permitted to use a throws clause for unchecked exceptions, but the
compiler does not require one
21
Exception Handling
Checked Exceptions – the try statement
 Second requirement, when using checked exceptions
 Method that throws a checked exception must make provision for dealing
with the exception
 Use try statement to make a try block
 Syntax
try{
Protect one or more statements here.
}
catch(Exception e) {
Report and recover from the exception here.
}
22
Exception Handling
Checked Exceptions – the catch statement
 catch block catches all exceptions of its type and subclasses of its type
 If there are multiple catch blocks that match a particular exception type, only
the first matching catch block executes
 Makes sense to use a catch block of a superclass when all catch blocks for that
class’s subclasses will perform same functionality
23
Exception Handling
Checked Exceptions – the finally Block
 Consists of finally keyword followed by a block of code enclosed in curly
braces
 Optional in a try statement
 If present, is placed after the last catch block
 Executes whether or not an exception is thrown in the corresponding try block
or any of its corresponding catch blocks
 Will not execute if the application exits early from a try block via method
System.exit
 Typically contains resource-release code
24
Sequence of Events for throw
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
Exception Handling
25
Sequence of Events for No throw
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
Exception Handling
26
Sequence of Events for finally clause
Preceding step
try block
throw statement
unmatched catch
matching catch
unmatched catch
next step
finally
Exception Handling
27
Exception Handling
28
Exceptional Flow of Control
 Exceptions break the normal flow of control.
 When an exception occurs, the statement that would normally execute next is
not executed.
 What happens instead depends on:
whether the exception is caught,
where it is caught,
what statements are executed in the ‘catch block’,
and whether you have a ‘finally block’.
Exception Handling
29
Catching a Exception Complete Template
try { // statement that could throw an exception
}
catch (<exception type> e) {
// statements that handle the exception
}
catch (<exception type> e) { //e higher in hierarchy
// statements that handle the exception
}
finally {
// release resources
}
//other statements
 At most one catch block executes
 finally block always executes once, whether there’s an error or not
Exception Handling
30
Compile Time Exception Example
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]){
File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
C:>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error:
unreported exception FileNotFoundException; must be caught or declared
to be thrown FileReader fr = new FileReader(file); ^ 1 error
Exception Handling
31
Run Time Exception Example
public class Unchecked_Demo {
public static void main(String args[]){
int num[]={1,2,3,4};
System.out.println(num[5]);
}
}
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
Exception Handling
32
Catching a Run Time Exception
public class Exception{
public static void main(String aa[]){
try{
int a[]=new int[1];
System.out.println(a[2]);
}
catch(Exception e){
System.out.println("Exception Caught");
}
finally{
System.out.println(“Finally Block");
}
System.out.println(“After Exception”);
}
}
Exception Handling
33
What may be the behavior of the previous
slide program if exception was not
handled?
Exception Handling – Multiple Catch Blocks
34
public class Exception{
public static void main(String aa[]){
int a[]=new int[5];
try{
System.out.println(a[1]/0);
}
catch(ArithmeticException e){
System.out.println("Divided By Zero");
}
catch(NullPointerException e){
System.out.println("Null Pointer Excdption");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Index Out of Bound");
}
System.out.println(“After Exception”);
}
35

More Related Content

What's hot

Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...Andrey Karpov
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2Akhil Mittal
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debuggingsalissal
 
Manual testing interview question by INFOTECH
Manual testing interview question by INFOTECHManual testing interview question by INFOTECH
Manual testing interview question by INFOTECHPravinsinh
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockschlebu
 
Implementing Blackbox Testing
Implementing Blackbox TestingImplementing Blackbox Testing
Implementing Blackbox TestingEdureka!
 
Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 

What's hot (18)

Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Debugging in .Net
Debugging in .NetDebugging in .Net
Debugging in .Net
 
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
PVS-Studio Static Analyzer as a Tool for Protection against Zero-Day Vulnerab...
 
Exception handling
Exception handlingException handling
Exception handling
 
Diving into VS 2015 Day2
Diving into VS 2015 Day2Diving into VS 2015 Day2
Diving into VS 2015 Day2
 
Error handling and debugging
Error handling and debuggingError handling and debugging
Error handling and debugging
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
12 exception handling
12 exception handling12 exception handling
12 exception handling
 
How to handle exceptions in Java Technology
How to handle exceptions in Java Technology How to handle exceptions in Java Technology
How to handle exceptions in Java Technology
 
Manual testing interview question by INFOTECH
Manual testing interview question by INFOTECHManual testing interview question by INFOTECH
Manual testing interview question by INFOTECH
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 
Exception handling
Exception handlingException handling
Exception handling
 
Testdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMockTestdriven Development using JUnit and EasyMock
Testdriven Development using JUnit and EasyMock
 
EasyMock for Java
EasyMock for JavaEasyMock for Java
EasyMock for Java
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Implementing Blackbox Testing
Implementing Blackbox TestingImplementing Blackbox Testing
Implementing Blackbox Testing
 
Exception handling
Exception handlingException handling
Exception handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 

Similar to Lecture 20-21

Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxVishuSaini22
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxsunilsoni446112
 
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdfVISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdfNALANDACSCCENTRE
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Info manual testing questions
Info manual testing questionsInfo manual testing questions
Info manual testing questionsSandeep
 
Dependable Software Development in Software Engineering SE18
Dependable Software Development in Software Engineering SE18Dependable Software Development in Software Engineering SE18
Dependable Software Development in Software Engineering SE18koolkampus
 
Manual testing interview questions
Manual testing interview questionsManual testing interview questions
Manual testing interview questionsBABAR MANZAR
 
Exception Handling in UiPath.pptx
Exception Handling in UiPath.pptxException Handling in UiPath.pptx
Exception Handling in UiPath.pptxApurbaSamanta9
 
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of ExceptionsfsfsfsdfsdfdsfsfsdfsdTypes of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsdssuserce9e9d
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsRandy Connolly
 
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01Anshuman Rai
 
Manual testing interview questions by infotech
Manual testing interview questions by infotech Manual testing interview questions by infotech
Manual testing interview questions by infotech suhasreddy1
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 

Similar to Lecture 20-21 (20)

VBscript
VBscriptVBscript
VBscript
 
Lecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptxLecture 1 Try Throw Catch.pptx
Lecture 1 Try Throw Catch.pptx
 
Lecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptxLecture 3.1.1 Try Throw Catch.pptx
Lecture 3.1.1 Try Throw Catch.pptx
 
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdfVISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
VISUAL_BASIC_LECTURE_NOTE_A_Z_MADE_EASY.pdf
 
6-Error Handling.pptx
6-Error Handling.pptx6-Error Handling.pptx
6-Error Handling.pptx
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Info manual testing questions
Info manual testing questionsInfo manual testing questions
Info manual testing questions
 
Exception handling
Exception handlingException handling
Exception handling
 
Lecture 22 - Error Handling
Lecture 22 - Error HandlingLecture 22 - Error Handling
Lecture 22 - Error Handling
 
Dependable Software Development in Software Engineering SE18
Dependable Software Development in Software Engineering SE18Dependable Software Development in Software Engineering SE18
Dependable Software Development in Software Engineering SE18
 
Manual testing interview questions
Manual testing interview questionsManual testing interview questions
Manual testing interview questions
 
Exception Handling in UiPath.pptx
Exception Handling in UiPath.pptxException Handling in UiPath.pptx
Exception Handling in UiPath.pptx
 
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of ExceptionsfsfsfsdfsdfdsfsfsdfsdTypes of Exceptionsfsfsfsdfsdfdsfsfsdfsd
Types of Exceptionsfsfsfsdfsdfdsfsfsdfsd
 
ASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation ControlsASP.NET 05 - Exception Handling And Validation Controls
ASP.NET 05 - Exception Handling And Validation Controls
 
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
Manualtestinginterviewquestionbyinfotech 100901071035-phpapp01
 
Manual testing interview questions by infotech
Manual testing interview questions by infotech Manual testing interview questions by infotech
Manual testing interview questions by infotech
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Debugging
DebuggingDebugging
Debugging
 

More from talha ijaz

More from talha ijaz (16)

Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Visual perception
Visual perceptionVisual perception
Visual perception
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
 
Introduction
IntroductionIntroduction
Introduction
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 

Recently uploaded

VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PPRINCE C P
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoSérgio Sacani
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxpradhanghanshyam7136
 
Luciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptxLuciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptxAleenaTreesaSaji
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfSELF-EXPLANATORY
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxUmerFayaz5
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )aarthirajkumar25
 
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxkessiyaTpeter
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...jana861314
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |aasikanpl
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsSérgio Sacani
 
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdfNAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdfWadeK3
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Lokesh Kothari
 

Recently uploaded (20)

VIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C PVIRUSES structure and classification ppt by Dr.Prince C P
VIRUSES structure and classification ppt by Dr.Prince C P
 
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Munirka Delhi 💯Call Us 🔝8264348440🔝
 
The Philosophy of Science
The Philosophy of ScienceThe Philosophy of Science
The Philosophy of Science
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on Io
 
Cultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptxCultivation of KODO MILLET . made by Ghanshyam pptx
Cultivation of KODO MILLET . made by Ghanshyam pptx
 
Luciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptxLuciferase in rDNA technology (biotechnology).pptx
Luciferase in rDNA technology (biotechnology).pptx
 
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdfBehavioral Disorder: Schizophrenia & it's Case Study.pdf
Behavioral Disorder: Schizophrenia & it's Case Study.pdf
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Animal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptxAnimal Communication- Auditory and Visual.pptx
Animal Communication- Auditory and Visual.pptx
 
Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )Recombination DNA Technology (Nucleic Acid Hybridization )
Recombination DNA Technology (Nucleic Acid Hybridization )
 
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptxSOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
SOLUBLE PATTERN RECOGNITION RECEPTORS.pptx
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
 
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdfNAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
NAVSEA PEO USC - Unmanned & Small Combatants 26Oct23.pdf
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Engler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomyEngler and Prantl system of classification in plant taxonomy
Engler and Prantl system of classification in plant taxonomy
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
 

Lecture 20-21

  • 2. Today’s Lecture  Defensive Programming  Exception Handling 2
  • 3. Defensive Programming What is Defensive Programming?  In a Client – Server Interaction where a server object only perform activities on client request.  While writing server class, a programmer can adopt two possible ways 1. They can assume that client objects will know what they are doing and will request services only in a sensible and well-defined way. 2. They can assume that server objects will operate in an essentially problematic environment in which all possible steps must be taken to prevent client objects from using them incorrectly.  Extreme views  Practically, scenario lies some where in between  A third possibility, of course, is an intentionally hostile client who is trying to break or find a weakness in the server. 3
  • 4. Defensive Programming Questions to Discuss  Different views - a useful base to discuss questions such as:  How much checking should a server’s methods perform on client requests?  How should a server report errors to its clients?  How can a client anticipate failure of a request to a server?  How should a client deal with failure of a request?  So far we have written all the classes with implicit trust that client will use these classes appropriately 4
  • 5. Defensive Programming Parameter Checking  A server object is most vulnerable when its constructor and methods receive external values through their parameters.  The values passed to a constructor are used to set up an object’s initial state, while the values passed to a method will be used to influence the overall effect of the method call and may change the state of the object and a result the method returns.  It is vital that a server object knows whether it can trust parameter values to be valid or whether it needs to check their validity for itself. 5
  • 6. Defensive Programming Server Error Reporting  Having protected a server object from performing an illegal operation through bad parameter values is all that the server writer needs to do.  Ideally we should like to avoid such error situations from arising in the first place.  Furthermore, it is often the case that incorrect parameter values are the result of some form of programming error in the client that supplied them.  Therefore, rather than simply programming around the problem in the server and leaving it at that, it is good practice for the server to make some effort to indicate that a problem has arisen, either to the client itself or to a human user or programmer.  Here we see three different nature of users 6
  • 7. Defensive Programming Notifying User  Print an error message  Two Problems with this Approach 1. They assume that the application is being used by a human user who will see the error message. There are many applications that run completely independently of a human user. An error message, or an error window, will go completely unnoticed. 2. Even where there is a human user to see the error message, it will be rare for that user to be in a position to do something about the problem.  Programs that print inappropriate error messages are more likely to annoy their users rather than achieve a useful outcome.  Except in a very limited set of circumstances, notifying the user is not a general solution to the problem of error reporting. 7
  • 8. Defensive Programming Notifying Client Object  There are two main ways to notify client object 1. A server can use a non-void return type (e.g boolean) of a method to return a value that indicates either success or failure of the method call. 2. A server can throw an exception if something goes wrong. 8
  • 9. Exceptions What is an Exception?  An Exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's Instructions.  An exception can occur for many different reasons, below given are some scenarios where exception occurs.  A user has entered invalid data.  A file that needs to be opened cannot be found.  A network connection has been lost in the middle of communications or the JVM has run out of memory.  Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. 9
  • 10. Exceptions Three Categories of Exception  Checked Exception : A checked exception is an exception that occurs at the compile time, these are also called as compile time exceptions. These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care of (handle) these exceptions.  Unchecked Exception : An Unchecked exception is an exception that occurs at the time of execution, these are also called as Runtime Exceptions, these include programming bugs, such as logic errors or improper use of an API. runtime exceptions are ignored at the time of compilation.  Error: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. 10
  • 11. Exception Handling What is Exception Handling?  The process of converting system error messages into user friendly error message is known as Exception handling.  This is one of the powerful feature of Java to handle run time error and maintain normal flow of java application. 11
  • 13. Exception Handling Methods with Description  public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor  public Throwable getCause() Returns the cause of the exception as represented by a Throwable object.  public String toString() Returns the name of the class concatenated with the result of getMessage()  public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. There are more method, Google for better understanding of Exception 13
  • 14. Exception Throwing Throwing an Exception  Throwing an exception is the most effective way a server object has of indicating that it is unable to fulfill a call on one of its methods.  One of the major advantages this has over using a special return value is that it is (almost) impossible for a client to ignore the fact that an exception has been thrown and carry on regardless.  Failure by the client to handle an exception will result in the application terminating immediately.  In addition, the exception mechanism is independent of the return value of a method, so it can be used for all methods, irrespective of the return type  An Exception is thrown using throw statement. 14
  • 15. Exception Throwing Throwing an Unchecked Exception Example  Here getDetails method is throwing an exception to indicate that passing a nullvalue for the key does not make sense because it is not a valid key. publicContactDetails getDetails(String key) { if(key == null){ throw new IllegalArgumentException( "null key in getDetails"); } return book.get(key); } 15
  • 16. Exception Throwing Throwing Exception Principles  Exception Mechanism is independent of the return value of method, so it can be used for all methods, irrespective of all return types  The place where an error is discovered will be distinct from where recovery is attempted  Discovery will be in server’s method  Recovery will be in the client  If recovery were possible at the point of discovery then there would be no point in throwing an exception 16
  • 17. Exception Throwing Throwing an Exception  Two stages involve in throwing exception 1. First, an exception object is created using the new keyword 2. the exception object is thrown using the throw keyword  When an exception object is created, a diagnostic string may be passed to its constructor.  This string is later available to the receiver of the exception via the exception object’s getMessage and toString methods.  The string is also shown to the user if the exception is not handled and leads to the termination of the program.  The exception type we have used here, IllegalArgumentException, is defined in the java.lang package and is regularly used to indicate that an inappropriate actual parameter value has been passed to a method or constructor. 17
  • 18. Exception Throwing Checked vs Unchecked Exceptions  Checked exceptions are intended for cases where the client should expect that an operation could fail (for example, if it tries to write to a disk, it should anticipate that the disk could be full).  In such cases, the client will be forced to check whether the operation was successful.  Unchecked exceptions are intended for cases that should never fail in normal operation—they usually indicate a program error.  For instance, a programmer would never knowingly try to get an item from a position in a list that does not exist, so when they do, it elicits an unchecked exception. 18
  • 19. Exception Throwing The Effect of an Exception  Two Effects 1. the effect in the method where the problem is discovered and the exception is thrown 2. the effect in the caller of the problem method  When an exception is thrown, the execution of the current method finishes immediately; it does not continue to the end of the method body  Consider the following contrived call to getDetails: String phone = details.getPhone();  The execution of these statements will be left incomplete 19
  • 20. Exception Throwing Preventing Object from Creation  An important use for exceptions is to prevent objects from being created if they cannot be placed in a valid initial state  This will usually be the result of inappropriate parameter values being passed to a constructor.  The process of throwing an exception from a constructor is exactly the same as throwing one from a method  An exception thrown from a constructor has the same effect on the client as an exception thrown from a method. 20
  • 21. Exception Handling Checked Exceptions – the throws clause  The first requirement of the compiler is that a method throwing a checked exception must declare that it does so in a throws clause added to the method’s header. public void saveToFile(String destinationFile) throws IOException  It is permitted to use a throws clause for unchecked exceptions, but the compiler does not require one 21
  • 22. Exception Handling Checked Exceptions – the try statement  Second requirement, when using checked exceptions  Method that throws a checked exception must make provision for dealing with the exception  Use try statement to make a try block  Syntax try{ Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } 22
  • 23. Exception Handling Checked Exceptions – the catch statement  catch block catches all exceptions of its type and subclasses of its type  If there are multiple catch blocks that match a particular exception type, only the first matching catch block executes  Makes sense to use a catch block of a superclass when all catch blocks for that class’s subclasses will perform same functionality 23
  • 24. Exception Handling Checked Exceptions – the finally Block  Consists of finally keyword followed by a block of code enclosed in curly braces  Optional in a try statement  If present, is placed after the last catch block  Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks  Will not execute if the application exits early from a try block via method System.exit  Typically contains resource-release code 24
  • 25. Sequence of Events for throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step Exception Handling 25
  • 26. Sequence of Events for No throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step Exception Handling 26
  • 27. Sequence of Events for finally clause Preceding step try block throw statement unmatched catch matching catch unmatched catch next step finally Exception Handling 27
  • 28. Exception Handling 28 Exceptional Flow of Control  Exceptions break the normal flow of control.  When an exception occurs, the statement that would normally execute next is not executed.  What happens instead depends on: whether the exception is caught, where it is caught, what statements are executed in the ‘catch block’, and whether you have a ‘finally block’.
  • 29. Exception Handling 29 Catching a Exception Complete Template try { // statement that could throw an exception } catch (<exception type> e) { // statements that handle the exception } catch (<exception type> e) { //e higher in hierarchy // statements that handle the exception } finally { // release resources } //other statements  At most one catch block executes  finally block always executes once, whether there’s an error or not
  • 30. Exception Handling 30 Compile Time Exception Example import java.io.File; import java.io.FileReader; public class FilenotFound_Demo { public static void main(String args[]){ File file=new File("E://file.txt"); FileReader fr = new FileReader(file); } } C:>javac FilenotFound_Demo.java FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown FileReader fr = new FileReader(file); ^ 1 error
  • 31. Exception Handling 31 Run Time Exception Example public class Unchecked_Demo { public static void main(String args[]){ int num[]={1,2,3,4}; System.out.println(num[5]); } } Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
  • 32. Exception Handling 32 Catching a Run Time Exception public class Exception{ public static void main(String aa[]){ try{ int a[]=new int[1]; System.out.println(a[2]); } catch(Exception e){ System.out.println("Exception Caught"); } finally{ System.out.println(“Finally Block"); } System.out.println(“After Exception”); } }
  • 33. Exception Handling 33 What may be the behavior of the previous slide program if exception was not handled?
  • 34. Exception Handling – Multiple Catch Blocks 34 public class Exception{ public static void main(String aa[]){ int a[]=new int[5]; try{ System.out.println(a[1]/0); } catch(ArithmeticException e){ System.out.println("Divided By Zero"); } catch(NullPointerException e){ System.out.println("Null Pointer Excdption"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("Index Out of Bound"); } System.out.println(“After Exception”); }
  • 35. 35