Exception handling in Java allows programs to deal with errors and unexpected conditions gracefully. The try block encloses code that might throw exceptions. When an exception is thrown, the runtime system searches the call stack for a catch block that can handle the exception. The finally block always executes after the try and catch blocks complete to ensure cleanup code runs. Custom exceptions can be created by extending the Exception class.
This is the material that I prepared for gathering best practices in exception handling that we aim to follow. I used the content stated in the references section.
This PPT has the basic instroduction of the Throwable class. it contains it's contructor and methods with explanations and example. i hope it may help you.
This is the material that I prepared for gathering best practices in exception handling that we aim to follow. I used the content stated in the references section.
This PPT has the basic instroduction of the Throwable class. it contains it's contructor and methods with explanations and example. i hope it may help you.
The exception hierarchy
Exception handling fundamentals
Try and catch
The consequences of an uncaught exception
Using multiple catch statements
Catching subclass exceptions
Nested try blocks
Throwing an exception
Re-throwing an exception
Using finally
Using throws
Java’s built-in exception
Creating exception subclasses
Explore the innovative world of trenchless pipe repair with our comprehensive guide, "The Benefits and Techniques of Trenchless Pipe Repair." This document delves into the modern methods of repairing underground pipes without the need for extensive excavation, highlighting the numerous advantages and the latest techniques used in the industry.
Learn about the cost savings, reduced environmental impact, and minimal disruption associated with trenchless technology. Discover detailed explanations of popular techniques such as pipe bursting, cured-in-place pipe (CIPP) lining, and directional drilling. Understand how these methods can be applied to various types of infrastructure, from residential plumbing to large-scale municipal systems.
Ideal for homeowners, contractors, engineers, and anyone interested in modern plumbing solutions, this guide provides valuable insights into why trenchless pipe repair is becoming the preferred choice for pipe rehabilitation. Stay informed about the latest advancements and best practices in the field.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
CFD analysis is incredibly effective at solving mysteries and improving the performance of complex systems!
Here's a great example: At a large natural gas-fired power plant, where they use waste heat to generate steam and energy, they were puzzled that their boiler wasn't producing as much steam as expected.
R&R and Tetra Engineering Group Inc. were asked to solve the issue with reduced steam production.
An inspection had shown that a significant amount of hot flue gas was bypassing the boiler tubes, where the heat was supposed to be transferred.
R&R Consult conducted a CFD analysis, which revealed that 6.3% of the flue gas was bypassing the boiler tubes without transferring heat. The analysis also showed that the flue gas was instead being directed along the sides of the boiler and between the modules that were supposed to capture the heat. This was the cause of the reduced performance.
Based on our results, Tetra Engineering installed covering plates to reduce the bypass flow. This improved the boiler's performance and increased electricity production.
It is always satisfying when we can help solve complex challenges like this. Do your systems also need a check-up or optimization? Give us a call!
Work done in cooperation with James Malloy and David Moelling from Tetra Engineering.
More examples of our work https://www.r-r-consult.dk/en/cases-en/
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Hierarchical Digital Twin of a Naval Power SystemKerry Sado
A hierarchical digital twin of a Naval DC power system has been developed and experimentally verified. Similar to other state-of-the-art digital twins, this technology creates a digital replica of the physical system executed in real-time or faster, which can modify hardware controls. However, its advantage stems from distributing computational efforts by utilizing a hierarchical structure composed of lower-level digital twin blocks and a higher-level system digital twin. Each digital twin block is associated with a physical subsystem of the hardware and communicates with a singular system digital twin, which creates a system-level response. By extracting information from each level of the hierarchy, power system controls of the hardware were reconfigured autonomously. This hierarchical digital twin development offers several advantages over other digital twins, particularly in the field of naval power systems. The hierarchical structure allows for greater computational efficiency and scalability while the ability to autonomously reconfigure hardware controls offers increased flexibility and responsiveness. The hierarchical decomposition and models utilized were well aligned with the physical twin, as indicated by the maximum deviations between the developed digital twin hierarchy and the hardware.
Final project report on grocery store management system..pdfKamal Acharya
In today’s fast-changing business environment, it’s extremely important to be able to respond to client needs in the most effective and timely manner. If your customers wish to see your business online and have instant access to your products or services.
Online Grocery Store is an e-commerce website, which retails various grocery products. This project allows viewing various products available enables registered users to purchase desired products instantly using Paytm, UPI payment processor (Instant Pay) and also can place order by using Cash on Delivery (Pay Later) option. This project provides an easy access to Administrators and Managers to view orders placed using Pay Later and Instant Pay options.
In order to develop an e-commerce website, a number of Technologies must be studied and understood. These include multi-tiered architecture, server and client-side scripting techniques, implementation technologies, programming language (such as PHP, HTML, CSS, JavaScript) and MySQL relational databases. This is a project with the objective to develop a basic website where a consumer is provided with a shopping cart website and also to know about the technologies used to develop such a website.
This document will discuss each of the underlying technologies to create and implement an e- commerce website.
2. Introduction
• A program can fail for just about any reason. Here are just a few
possibilities:
• The code tries to connect to a website, but the Internet connection is down.
• You made a coding mistake and tried to access an invalid index in an array.
• One method calls another with a value that the method doesn’t support.
• The code tries to connect to a website, but the power goes off.
• You are trying to create an object of some class, Class Not Found
• You try to read from a File, File Not Found
• The code tries to connect to database, database is not available, connection
failed….
3. Introduction
• Some of these are coding mistakes. Others are completely beyond
your control.
• Your program can’t help it if the Internet connection goes down.
What it can do is deal with the situation.
• Happy path, Unhappy path
• When Java was a kid…
• These are the two approaches Java uses when dealing with
exceptions. A method can handle the exception case itself or make it
the caller’s responsibility.
6. When we can use Exceptions?
• Exceptions can and do occur all the time, even in solid program code.
• When you write more advanced programs, you’ll need to deal with
failures in accessing files, networks, and outside services.
• Exceptions are used when “something goes wrong.”
• Exception while Search not found – return a special value
• An exception should be reserved for exceptional conditions like
names being null.
• An exception forces the program to deal with them or end.
• With the exception if left unhandled, whereas a return code could be
accidentally ignored and cause problems later in the program.
• An exception is like shouting, “Deal with me!”
7. Without Exception handling
• Consider statements in flow
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs - statements 6 to 9 will not get executed
statement 6;
statement 7;
Statement 8;
Statement 9;
11. After Handling Exceptions
• The exception handling in java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.- Smooth Termination
• Exception is an event that alters program flow.
• Consider statements in flow
statement 1;
statement 2;
statement 3;
statement 4;
statement 5; // If we perform exception handling - statements 6 to 9 will get executed
statement 6;
statement 7;
Statement 8;
Statement 9;
14. Understanding Exception Types: Error
• Error means something went so horribly wrong that your program
should not attempt to recover from it.
• These are exceptional conditions that are external to the application,
and that the application usually cannot anticipate or recover from.
• Ex. suppose that an application successfully opens a file for input, but
is unable to read the file because of a hardware or system
malfunction.
• The unsuccessful read will throw java.io.IOError.
• Errors are not subject to the Catch or Specify Requirement. Errors are
those exceptions indicated by Error and its subclasses.
15. Exception Types: Runtime Exception
• These are exceptional conditions that are internal to the application, and
that the application usually cannot anticipate or recover from.
• These usually indicate programming bugs, such as logic errors or improper
use of an API.
• Ex1: consider the application described previously that passes a file name
to the constructor for FileReader. If a logic error causes a null to be passed
to the constructor, the constructor will throw NullPointerException.
• The application can catch this exception, but it probably makes more sense
to eliminate the bug that caused the exception to occur.
• Runtime exceptions tend to be unexpected but not necessarily fatal.
• Ex2: accessing an invalid array index is unexpected.
• Runtime exception is defined as the RuntimeException class and its
subclasses.
17. Understanding Exception Types
• A checked exception includes Exception and all subclasses that do not extend
RuntimeException.
• Checked exceptions tend to be more anticipated—for example, trying to read a
file that doesn’t exist.
• Checked exceptions are checked at compile-time.
• Java has a rule called the handle or declare rule.
• For checked exceptions, Java requires the code to either handle them or declare
them in the method signature.
• For example, this method declares that it might throw an exception:
void fall() throws Exception {
throw new Exception();
}
18. Checked Exception
• These are exceptional conditions that a well-written application should
anticipate and recover from.
• For example, suppose an application prompts a user for an input file name,
then opens the file by passing the name to the constructor for
java.io.FileReader. Normally, the user provides the name of an existing,
readable file, so the construction of the FileReader object succeeds, and
the execution of the application proceeds normally. But sometimes the
user supplies the name of a nonexistent file, and the constructor throws
java.io.FileNotFoundException. A well-written program will catch this
exception and notify the user of the mistake, possibly prompting for a
corrected file name.
• Checked exceptions are subject to the Catch or Specify Requirement. All
exceptions are checked exceptions, except for those indicated by Error,
RuntimeException, and their subclasses.
21. The try block
The first step in constructing an exception handler is to enclose the
code that might throw an exception within a try block. In general, a try
block looks like the following:
try {
code
}
catch and finally blocks . . .
22. What happens when an Exception is thrown?
• When an error occurs within a method, the method creates an object
and hands it off to the runtime system.
• The object, called an exception object, contains information about the
1. Error, including its type and
2. The state of the program when the error occurred.
23. Creating an exception object and handing it to the
runtime system is called throwing an exception.
24. The call stack
After a method throws an
exception, the runtime
system attempts to find
something to handle it.
The set of possible
"somethings" to handle
the exception is the
ordered list of methods
that had been called to get
to the method where the
error occurred. The list of
methods is known as
the call stack.
Method where error occurred
Method without an exception
handler
Method with an exception
handler
main
Method call
Method call
Method call
25. Searching the call stack for the exception handler
Method where error occurred
Method without an exception
handler
Method with an exception
handler
main
Looking for
appropriate
handler
Looking for
appropriate
handler
Throws Exception
Frorward Exception
Catches some other
Exception
26. Searching the call stack for the exception
handler
• The runtime system searches the call stack for a method that contains a
block of code that can handle the exception. This block of code is called
an exception handler. The search begins with the method in which the
error occurred and proceeds through the call stack in the reverse order in
which the methods were called. When an appropriate handler is found, the
runtime system passes the exception to the handler. An exception handler
is considered appropriate if the type of the exception object thrown
matches the type that can be handled by the handler.
• The exception handler chosen is said to catch the exception. If the runtime
system exhaustively searches all the methods on the call stack without
finding an appropriate exception handler, as shown in the next figure, the
runtime system (and, consequently, the program) terminates.
27. How to handle exception?
• We must use one of these pairs to handle the exception...
1. try - catch - [ similar to if else]
2. try - catch- finally
3. Try – multiple catch - finally
4. try - finally
28. i=0,
Income/0
Creates object of Exception,
search for catch block
Prints Exception type and
information
Executes finally block
Skips
execution
till catch
found
Resumes with rest of
the code after finally
1
30. Whichever exception occurs,
that matching catch block is
executed
Finally block gets executed
Rest of the code gets executed
after finally
Rest of the code gets executed
out of outer try block
Outer finally block gets
executed
2
32. Exception occurred, but no matching
catch block found
Finally block gets executed
Skipped
Rest of the code gets executed
Exception caught here
In case No matching catch block found in
inner try, nearest matching block is – Outer
catch block
Executes finally block of
outer try
3
38. Use of finally block
• The finally block always executes when the try block exits.
• This ensures that the finally block is executed even if an unexpected
exception occurs.
• But finally is useful for more than just exception handling — it allows
the programmer to avoid having cleanup code accidentally bypassed
by a return, continue, or break. Putting cleanup code in a finally block
is always a good practice, even when no exceptions are anticipated.
• Note: If the JVM exits while the try or catch code is being executed,
then the finally block may not execute. Likewise, if the thread
executing the try or catch code is interrupted or killed, the finally
block may not execute even though the application as a whole
continues.
39. Use of finally block
• The runtime system always executes the statements within the finally block
regardless of what happens within the try block. So it's the perfect place to
perform cleanup.
• The following finally block for the method cleans up and then closes the
PrintWriter.
• The finally block is a key tool for preventing resource leaks. When closing a file or
otherwise recovering resources, place the code in a finally block to ensure that
resource is always recovered.
finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
}
40. The try-with-resources Statement
• Consider using the try-with-resources statement in these situations, which
automatically releases system resources when no longer needed.
1. static String readFirstLineFromFile(String path) throws IOException {
2. try (BufferedReader br = new BufferedReader(new FileReader(path))) {
3. return br.readLine();
4. }
5. }
• This example reads the first line from a file. It uses an instance of
BufferedReader to read data from the file. BufferedReader is a resource
that must be closed after the program is finished with it.
41. The try-with-finally Statement
• Prior to Java SE 7, you can use a finally block to ensure that a resource is closed
regardless of whether the try statement completes normally or abruptly. The following
example uses a finally block instead of a try-with-resources statement:
1. static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException {
2. BufferedReader br = new BufferedReader(new FileReader(path));
3. try {
4. return br.readLine();
5. } finally {
6. if (br != null) br.close();
7. }
8. }
42. Throwing an Exception
• The throw keyword tells Java you want some other part of the code to
deal with the exception.
1. throw new Exception();
2. throw new Exception("Ow! I fell.");
• Above examples create a new object of type Exception and throw it.
• The Java throw keyword is used to explicitly throw an exception.
• We can throw either checked or unchecked exception.
• It is s mainly used to throw custom exception.
43. Specifying the Exceptions Thrown by a Method
using “throws” keyword
• To specify or to declare that method can throw exceptions, add a throws
clause to the method declaration for the that method.
• The throws clause comprises the throws keyword followed by a comma-
separated list of all the exceptions thrown by that method. The clause goes
after the method name and argument list and before the brace that defines
the scope of the method; here's an example.
public void writeList() throws IOException, IndexOutOfBoundsException {..}
• Here, IndexOutOfBoundsException is an unchecked exception; including it
in the throws clause is not mandatory.
• You could just write the following.
public void writeList() throws IOException {..}
47. Catching More Than One Type of Exception
with One Exception Handler
• In Java 7, catch block has been improved to handle multiple
exceptions in a single catch block. If you are catching multiple
exceptions and they have similar code, then using this feature will
reduce code duplication.
• In the catch clause, specify the types of exceptions that block can
handle, and separate each exception type with a vertical bar (|):
49. Chained Exceptions
• Exception handlers can do more than just print error messages or halt the
program. They can do error recovery, prompt the user to make a decision,
or propagate the error up to a higher-level handler using chained
exceptions.
• Throwing an exception along with another exception forms a chained
exception.
• In the preceding section, the catch block rethrows the original exception.
Sometimes, you may need to throw a new exception (with additional
information) along with the original exception.
• This is called chained exceptions.
• See example in next slide.
50. method2() is called from method1()
throws Exception
Catch block of caller
method gets executed
Catch block of caller
method gets executed
52. Defining Custom Exception Classes
• You can define a custom exception class by extending the
java.lang.Exception class.
• Java provides quite a few exception classes. Use them whenever
possible instead of defining your own exception classes. However, if
you run into a problem that cannot be adequately described by the
predefined exception classes, you can create your own exception
class, derived from Exception or from a subclass of Exception, such as
IOException.
55. Exception Handling with MethodOverriding in
Java
• There are many rules if we talk about methodoverriding with
exception handling.
• If the superclass method does not declare an exception
• If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
• If the superclass method declares an exception
• If the superclass method declares an exception, subclass overridden method
can declare same, subclass exception or no exception but cannot declare
parent exception.
56. If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
Compilation Error
57. If the superclass method does not declare an exception, subclass overridden method cannot
declare the checked exception but can declare unchecked exception.
Output:
child
58. If the superclass method declares an exception, subclass overridden method can declare same,
subclass exception or no exception but cannot declare parent exception.
Output:
Compilation error
Subclass overridden method can declares same
exception – this is valid
59. Example in case subclass overridden method declares subclass exception
60. Advantages of Exceptions
• https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta
ges.html
61. References
• http://www.geeksforgeeks.org
• Introduction to Java Programming, Comprehensive Version (10th
Edition), Y. Daniel Liang
• https://docs.oracle.com/javase/tutorial/essential/exceptions/advanta
ges.html
• https://www.javatpoint.com
• https://www.journaldev.com
• OCA Oracle Certified Associate Java SE 8 Programmer Study Guide
Exam 1Z0 808