The document discusses event handling and exceptions in Java. It covers event-driven programming, event classes, listeners, and delegation models. It also covers exception handling, common exception types like IOException and NullPointerException, using try/catch blocks to handle exceptions, and best practices for exception handling in Java programs.
Applet Basics,
Applet Organization and Essential Elements,
The Applet Architecture,
A Complete Applet Skeleton,
Applet Initialization and Termination,
Requesting Repainting
The update() Method,
Using the Status Window
Passing parameters to Applets
The Applet Class
Event Handling The Delegation Event Model
Events,
Using the Delegation Event Model,
More Java Keywords.
Applet Basics,
Applet Organization and Essential Elements,
The Applet Architecture,
A Complete Applet Skeleton,
Applet Initialization and Termination,
Requesting Repainting
The update() Method,
Using the Status Window
Passing parameters to Applets
The Applet Class
Event Handling The Delegation Event Model
Events,
Using the Delegation Event Model,
More Java Keywords.
This presentation introduces Java Applet and Java Graphics in detail with examples and finally using the concept of both applet and graphics code the analog clock project to depict how to use them in real life challenges and applications.
This presentation introduces Java Applet and Java Graphics in detail with examples and finally using the concept of both applet and graphics code the analog clock project to depict how to use them in real life challenges and applications.
unit 4 msbte syallbus for sem 4 2024-2025AKSHAYBHABAD5
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on the notifications, alerts, and approval requests using Slack for Bonterra Impact Management. The solutions covered in this webinar can also be deployed for Microsoft Teams.
Interested in deploying notification automations for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
2. The process of responding to an
event. Window programs are
said to be event-driven because
they operate by performing
actions in response to events.
3. Contents
The Delegation Event Model
Event Classes
Event Listeners
Adapter Classes
Inner Classes
Anonymous Inner Classes
4. The Delegation Event Model
Applet is event-driven.
Delegation Event model: JDK 1.1 introduced
12. Exception in Java are classified
on the basis of the exception
handled by the java compiler.
13. Contents:
•Exception Handling in Java
I. Introduction
II. Common Exceptions
III. “Catching” Exceptions
IV. The Throwable Superclass
V. Effectively using try-catch
VI. Final thoughts of Exceptions
•Type of Built-In Exceptions
I. Checked Exception
II. Unchecked Exception
•Exception Hierarchy
15. Exception Handling in Java
I. Introduction
An exception is an error thrown by a class or method
reporting an error in operation. For example, dividing by zero
is undefined in mathematics, and a calculation can fail if this
winds up being the case because of an error in user input. In
this particular case an ArithmeticException is thrown, and
unless the programmer looks for this exception and manually
puts in code to handle it, the program will crash stating the
exception thrown and a stack trace, which would be unhelpful
to a casual user of a Java program. If the programmer handles
the exception, he could deliver a useful error to the user and
return the user to the beginning of the program so that they
could continue to use it.
16. Exception Handling in Java
II. Common Exceptions
There are many different exceptions that can be thrown by a
program, and the Java API contains quite a few. A lot are
contained in the default package, java.lang; however, when
you start using more functionality such as
AWT, Swing, or java.io, the packages may also contain
additional exceptions thrown by those libraries. As you start
expanding the functionality, it might be a good idea to look
at potential exceptions in the package and when they might
be thrown in the course of your application.
17. Exception Handling in Java
II. Common Exceptions
Here is a primer of some:
ArithmeticException--thrown if a program attempts to
perform division by zero
ArrayIndexOutOfBoundsException--thrown if a program
attempts to access an index of an array that does not exist
StringIndexOutOfBoundsException--thrown if a program
attempts to access a character at a non-existent index in
a String
NullPointerException--thrown if the JVM attempts to
perform an operation on an Object that points to no
data, or null
Continuation:
18. Exception Handling in Java
II. Common Exceptions
NumberFormatException--thrown if a program is
attempting to convert a string to a numerical datatype, and
the string contains inappropriate characters (i.e. 'z' or 'Q')
ClassNotFoundException--thrown if a program can not find
a class it depends at runtime (i.e., the class's ".class" file
cannot be found or was removed from the CLASSPATH)
IOException--actually contained in java.io, but it is thrown if
the JVM failed to open an I/O stream
As I said before, many different exceptions exist, and
you should probably use your API documentation to learn
about additional exceptions that may apply to your
particular application.
Continuation:
19. Exception Handling in Java
III. “Catching” Exceptions
The java language contains keywords used specifically for
testing for and handling exceptions. The ones we will be
using here are try and catch, and they must be used in
conjunction with one another. They sort of work like if-else:
try{
/*
Contains code to be tested
*/
}catch(Exception e){
/*
Contains code to be executed if instanced of Exception is
caught
*/}
20. Exception Handling in Java
III. “Catching” Exceptions
The catch statement can look for all exceptions, using
the Exception superclass, or it can catch a specific
exception that you think could be thrown in the code you
are testing with the tryblock. You can even have
multiple catch blocks to catch and execute custom code for
a number of different errors. A good thing to note would be
that any particular exception that is caught is compared
with each catch statement sequentially; so it is a good idea
to put more generic exceptions, like Exception, towards the
bottom of the list.
Continuation:
21. Exception Handling in Java
IV. The Throwable Superclass
The catch statement also stores an instance of the exception
that was caught in the variable that the programmer uses, in
the previous example Exception e. While all exceptions are
subclasses of Exception, Exception itself is a subclass
of Throwable, which contains a nice suite of methods that
you can use to get all kinds of information to report about
your exceptions:
•getMessage()--returns the error message reported by the
exception in a String
•printStackTrace()--prints the stack trace of the exception to
standard output, useful for debugging purposes in locating
where the exception occurred
22. Exception Handling in Java
IV. The Throwable Superclass
•printStackTrace(PrintStream s)--prints the stack trace to an
alternative output stream
•printStackTrace(PrintWriter s)--prints the stack trace to a
file, this way you can log stack traces transparent to the user
or log for later reference
•toString()--if you just decide to print out the exception it
will print out this: NAME_OF_EXCEPTION: getMessage().
Using the catch you now have control over what the error
message is and where it goes.
Continuation:
23. Exception Handling in Java
V. Effectively using try-catch
In this section, I'm going to give you a few code samples on
using try-catch blocks to give you an idea of the flexibility
you as a programmer have over exceptions in your programs.
The scenario is a user has input a file name to a program of a
file that does not exist. In this scenario we are going to be
using a text-based program; however, in a graphical
environment you can easily use the catch block to draw
dialog boxes. In the first example, we want to print a useful
error message and exit the program gracefully, saving the
user from the confusing stack trace with something useful:
24. Exception Handling in Java
V. Effectively using try-catch
try{
BufferedReader in = new BufferedReader(new
FileReader(userInput));
System.out.println(in.readLine())
}catch(IOException e){
System.err.println(e.getMessage());
System.err.println("Error: " + userInput + " is not a valid
file. Please verify that the file exists and that you have access
to it.");
System.exit(1);
}
Continuation:
25. Exception Handling in Java
V. Effectively using try-catch
Here, System.err.println() prints the error message
to standard error output which is a high priority buffer
that is used to report error messages to the console. If you're
being a good programmer, you have separate methods that
handle the different functionality of your programs; this way
you can easily start the program from a previous place in the
program before an exception occurs. In this next
example, the user inputs the filename through the
function getUserInput() elsewhere in the program; we want
to report the "helpful error message" to the user and return
the user to a place where he can enter a new filename.
Continuation:
26. Exception Handling in Java
V. Effectively using try-catch
try{
BufferedReader in = new BufferedReader(new
FileReader(userInput));
return in.readLine();
}catch(IOException e){
System.err.println(e.getMessage());
System.err.println("Error: " + userInput + " is not a valid
file. Please verify that the file exists and that you have access
to it.");
return getFileInput(getUserInput());
}
Continuation:
27. Exception Handling in Java
V. Effectively using try-catch
Now you have an idea of how you can control your
programs once an exception is thrown, and this should give
you the basic idea of how to work with exceptions in the Java
language.
Continuation:
28. Exception Handling in Java
VI. Final thoughts of Exceptions
The best way to prevent your application from crashing from
exceptions is to avoid exceptions in the first place. It is much
more costly for a system to catch and handle exceptions
than to account for potential errors directly in your code. A
lot of times, an exception can point to a problem in the
programmer's logic rather than in the user's use of the
program. You should look for the cause of exceptions, and
try to understand why it occurred and make sure that you
really had considered everything. You will be making far
more resilient and robust applications.
Continuation:
29. Types of Built In Exception
I. Checked Exception
These exception are the object of the Exception class or
any of its subclasses except Runtime Exception class.
These condition arises due to invalid input, problem
with your network connectivity and problem in
database.java.io.IOException is a checked exception.
This exception is thrown when there is an error in
input-output operation. In this case operation is
normally terminated.
30. Types of Built In Exception
List of Checked Exceptions
Exception Reason for Exception
This Exception occurs when Java run-time system fail to find the
ClassNotFoundException
specified class mentioned in the program
This Exception occurs when you create an object of an abstract
Instantiation Exception
class and interface
This Exception occurs when you create an object of an abstract
Illegal Access Exception
class and interface
This Exception occurs when the method you call does not exist in
Not Such Method Exception
class
31. Types of Built In Exception
II. Unchecked Exception
These Exception arises during run-time ,that occur due
to invalid argument passed to method. The java
Compiler does not check the program error during
compilation.
For Example when you divide a number by zero, run-
time exception is raised.
32. Types of Built In Exception
List of Unchecked Exceptions
Exception Reason for Exception
These Exception occurs, when you divide a number by zero
Arithmetic Exception
causes an Arithmetic Exception
These Exception occurs, when you try to assign a reference
Class Cast Exception variable of a class to an incompatible reference variable of
another class
These Exception occurs, when you assign an array which is not
Array Store Exception
compatible with the data type of that array
These Exception occurs, when you assign an array which is not
Array Index Out Of Bounds Exception
compatible with the data type of that array
These Exception occurs, when you try to implement an application
Null Pointer Exception
without referencing the object and allocating to a memory
These Exception occurs, when you try to convert a string variable
Number Format Exception in an incorrect format to integer (numeric format) that is not
compatible with each other
Negative ArraySizeException These are Exception, when you declare an array of negative size.
33. An exception is a problem that arises during the execution of a program. An
exception can occur for many different reasons, including the following:
• 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.
34. • Checked exceptions: A checked exception is an exception that is
typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored
at the time of compilation.
• Runtime exceptions: A runtime exception is an exception that
occurs that probably could have been avoided by the programmer. As
opposed to checked exceptions, runtime exceptions are ignored at the
time of compliation.
• Errors: 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.
35. All exception classes are subtypes of the java.lang.Exception class. The exception
class is a subclass of the Throwable class. Other than the exception class there is
another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions
normally happen in case of severe failures, which are not handled by the java
programs. Errors are generated to indicate errors generated by the runtime
environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
The Exception class has two main subclasses : IOException class and
RuntimeException Class.
36. SN Methods with Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable
constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
3 public String toString()
Returns the name of the class concatenated with the result of getMessage()
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents the top of the
call stack, and the last element in the array represents the method at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in
the stack trace.
37. A method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block (or blocks) that
follows the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.
38. The following is an array is declared with 2 elements. Then the code tries
E to access the 3rd element of the array which throws an exception.
// File Name : ExcepTest.java
X import java.io.*;
public class ExcepTest{
A public static void main(String args[]){
try{
int a[] = new int[2];
M System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
P }
System.out.println("Exception thrown :" + e);
System.out.println("Out of the block");
L }
}
E This would produce following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block
39. A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any
number of them after a single try. If an exception occurs in the protected code, the
exception is thrown to the first catch block in the list. If the data type of the exception
thrown matches ExceptionType1, it gets caught there. If not, the exception passes
down to the second catch statement. This continues until the exception either is
caught or falls through all catches, in which case the current method stops execution
and the exception is thrown down to the previous method on the call stack.
40. E Here is code segment showing how to use multiple try/catch statements.
X
try
A {
file = new FileInputStream(fileName);
M x = (byte) file.read();
}catch(IOException i)
{
P i.printStackTrace();
return -1;
L }catch(FileNotFoundException f) //Not valid!
{
f.printStackTrace();
E }
return -1;
41. If a method does not handle a checked exception, the method must
declare it using the throwskeyword. The throws keyword appears at the end of a
method's signature.
You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword. Try to understand the
different in throws and throw keywords.
The following method declares that it throws a RemoteException:
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
// Method implementation
throw new RemoteException();
}
//Remainder of class definition
}
42. A method can declare that it throws more than one exception, in which case
the exceptions are declared in a list separated by commas. For example, the following
method declares that it throws a RemoteException and an
InsufficientFundsException:
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
InsufficientFundsException
{
// Method implementation
}
//Remainder of class definition
}
43. The finally keyword is used to create a block of code that follows a try block.
A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code. A finally block appears at the
end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
44. public class ExcepTest{
E public static void main(String args[]){
int a[] = new int[2];
X try{
System.out.println("Access element three :" + a[3]);
}catch(ArrayIndexOutOfBoundsException e){
A }
System.out.println("Exception thrown :" + e);
M finally{
a[0] = 6;
System.out.println("First element value: " +a[0]);
P }
System.out.println("The finally statement is executed");
L }
}
E This would produce following result:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed
45. You can create your own exceptions in Java. Keep the following points in mind
when writing your own exception classes:
• All exceptions must be a child of Throwable.
• If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
• If you want to write a runtime exception, you need to extend the
RuntimeException class.
We can define our own Exception class as below:
class MyException extends Exception{
}
You just need to extend the Exception class to create your own Exception
class. These are considered to be checked exceptions. The following
InsufficientFundsException class is a user-defined exception that extends the
Exception class, making it a checked exception. An exception class is like any other
class, containing useful fields and methods.
46. // File Name InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends
Exception
{
private double amount;
public InsufficientFundsException(double
amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}
To demonstrate using our user-defined exception, the following CheckingAccount
class contains a withdraw() method that throws an InsufficientFundsException.
Continuation
47. // File Name CheckingAccount.java {
import java.io.*; if(amount <= balance)
public class CheckingAccount { balance -= amount; }
{ else
private double balance; {
private int number; double needs = amount -
public CheckingAccount(int balance;
number) throw new
{ InsufficientFundsException(needs);
this.number = number; }
} }
public void deposit(double public double getBalance()
amount) {
{ return balance;
balance += amount; }
} public int getNumber()
public void withdraw(double {
amount) throws return number;
}
InsufficientFundsException }
Continuation
48. The following BankDemo program demonstrates invoking the deposit() and
withdraw() methods of CheckingAccount.
// File Name BankDemo.java
public class BankDemo c.withdraw(100.00);
{
public static void main(String [] System.out.println("nWithdrawing
args) $600...");
{ c.withdraw(600.00);
CheckingAccount c = new
CheckingAccount(101); }catch(InsufficientFundsException e)
System.out.println("Depositing {
$500..."); System.out.println("Sorry,
c.deposit(500.00); but you are short $"
try +
{ e.getAmount());
e.printStackTrace();
System.out.println("nWithdrawing }
$100..."); }
}
Continuation
49. Compile all the above three files and run BankDemo, this would
produce following result:
Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Continuation
51. B
BatchUpdateException
BrokenBarrierException
C
CertificateException
ChangedCharSetException
CharConversionException
CharacterCodingException
ClassNotFoundException
CloneNotSupportedException
ClosedChannelException
D
DataFormatException
DatatypeConfigurationException
52. D
DestroyFailedException
E
EOFException
ExecutionException
ExpandVetoException
F
FileLockInterruptionException
FileNotFoundException
FishFaceException
FontFormatException
G
GSSException
53. G
GeneralSecurityException
I
IIOException
IOException
IllegalAccessException
IllegalArgumentException
IllegalClassFormatException
IllegalStateException
IndexOutOfBoundsException
InputMismatchException
InstantiationException
InterruptedException
55. L
LastOwnerException
LineUnavailableException
M
MalformedURLException
MarshalException
MidiUnavailableException
MimeTypeParseException
N
NamingException
NegativeArraySizeException
NoSuchElementException
NoSuchFieldException
NoSuchMethodException
57. P
PropertyVetoException
ProtocolException
R
RefreshFailedException
RemarshalException
RemoteException
RuntimeException
S
SAXException
SOAPException
SQLException
SQLWarning
SSLException
61. SAMPLE JAVA PROGRAM 1:
import java.io.*;
// A Java application to demonstrate making your own Exception class
// This program catches the exception when the word "client" is
// entered incorrectly.
public class TestException
{
static String s = "";
public static void main (String args[])
{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader buf = new BufferedReader(is);
System.out.println("Enter the word you cannot spell: ");
try
62. {
s = buf.readLine();
}
catch (IOException e)
{
System.out.println("IOException was " + e.getMessage());
}
try
{
checkSpelling(); // this method throws SpellException
}
catch (SpellException se) // but it is caught here
{
System.out.println("Spell exception was: " + se.getError());
}
} // end main
63. SAMPLE JAVA PROGRAM 2:
// Check spelling of typed in word. Throw exception if wrong.
// Note how this method specifies that it throws such and such
// exception. Does not have to be caught here.
private static void checkSpelling() throws SpellException
{
if (s.equalsIgnoreCase("client"))
System.out.println("OK");
else
throw new SpellException("Cannot spell client");
}
} // end main class