You are on page 1of 39

Java: exception handling

ch - 11
• Java Exception Handling is a mechanism to handle runtime errors and exceptions
that occur during the execution of a Java program. Exceptions in Java are objects
that are created at runtime when an abnormal situation arises in a program.
These abnormal situations could be due to an error in the program logic or
unexpected external factors such as input/output errors, hardware errors, or
network errors.
• Java provides a comprehensive Exception Handling framework that allows
developers to handle exceptions in their code in a systematic and efficient
manner. The framework consists of three key components:
1. Try-catch blocks: These blocks are used to enclose the code that may throw an
exception. If an exception occurs, the code inside the catch block is executed to
handle the exception.
2.Throwing exceptions: This is a mechanism used to signal that an error or
exceptional condition has occurred. It allows a method to signal that it has
encountered an error, without having to handle the error itself.
3.Exception classes: Java provides a set of pre-defined exception classes that can be
used to represent different types of exceptions. These classes are organized in a
hierarchy, with the base class being Throwable, which is the superclass of all
exceptions.
termination model of exception handling
• After the exception is handled, program control does not return to the
throw point, because the try block has expired (and its local variables
have been lost). Rather, control resumes after the last catch block.
This is known as the termination model of exception handling.
• Some languages use the resumption model of exception handling, in
which, after an exception is handled, control resumes just after the
throw point.
• Exception handling is designed to process synchronous errors, which occur when a
statement executes. Common examples we’ll see throughout the book are out-of-
range array
• indices, arithmetic overflow (i.e., a value outside the representable range of values),
division by zero, invalid method parameters, thread interruption (as we’ll see in
Chapter 26)
• and unsuccessful memory allocation (due to lack of memory). Exception handling is
not
• designed to process problems associated with asynchronous events (e.g., disk I/O
completions, network message arrivals, mouse clicks and keystrokes), which occur in
parallel with,
• and independent of, the program’s flow of control.
• All Java exception classes inherit directly or indirectly from class
Exception. a small portion of the inheritance hierarchy for class
Throwable (a subclass of Object), which is the superclass of class
Exception. Only Throwable objects can be used with the exception-
handling mechanism.
Portion of class Throwable’s inheritance
hierarchy
checked exceptions and unchecked
exceptions
• All exception types that are direct or indirect subclasses of class RuntimeException
(package java.lang) are unchecked exceptions. These are typically caused by defects in
your program’s code. Examples of unchecked exceptions include
ArrayIndexOutOfBoundsExceptions and ArithmeticExceptions.
• All classes that inherit from class Exception but not class RuntimeException are
considered to be checked exceptions. Such exceptions are typically caused by
conditions that are not under the control of the program—for example, in file
processing, the program can’t open a file because the file does not exist. Classes that
inherit from class Error are considered to be unchecked.
• Unchecked exceptions typically can be prevented by proper coding. For example, the
unchecked ArithmeticException thrown by method quotient (lines 9–13) in Fig. 11.2
can be avoided if the method ensures that the denominator is not zero before
attempting to perform the division.
• Only the First Matching catch Executes
• Programs that obtain certain types of resources must return them to the
system explicitly to avoid so-called resource leaks. files, database
connections and network connections that are not closed properly after
they’re no longer needed might not be available for use in other
programs.
• A subtle issue is that Java does not entirely eliminate memory leaks. Java
will not garbagecollect an object until there are no remaining references
to it. Thus, if you erroneously keepreferences to unwanted objects,
memory leaks can occur. To help avoid this problem, set reference-type
variables to null when they’re no longer needed.
finally block
• The finally block (which consists of the finally keyword, followed by code enclosed in
curly braces), sometimes referred to as the finally clause, is optional. If it’s present,
it’s placed after the last catch block. If there are no catch blocks, the finally block
immediately follows the try block.
• finally block executes even if an exception is not thrown in the corresponding try
block.
• Because a finally block almost always executes, it typically contains resource-release
code. Suppose a resource is allocated in a try block. If no exception occurs, the catch
blocks are skipped and control proceeds to the finally block, which frees the resource.
• If an exception that occurs in a try block cannot be caught by one of that try block’s
catch handlers, the program skips the rest of the try block and control proceeds to the
finally block.
Rethrow
• Exceptions are rethrown when a catch block, upon receiving an
exception, decides either that it cannot process that exception or that
it can only partially process it
• System.out and System.err are streams—sequences of bytes.
• While System.out (known as the standard output stream) displays a
program’s output, System.err (known as the standard error stream)
displays a program’s errors.
• Chained exceptions enable an exception object to maintain the
complete stack-trace information from the original exception.
stack unwinding
• In Java, when an exception is thrown and not caught by the current method,
the exception is passed up the call stack until a matching catch block is found.
This process of passing the exception up the call stack is known as "stack
unwinding."
• When an exception is thrown in a method, the method immediately
terminates and the exception is propagated up the call stack to the calling
method. If the calling method has a matching catch block for the exception
type, the catch block is executed, and the exception is handled. If the calling
method does not have a matching catch block, the exception is propagated up
the call stack again, until a matching catch block is found or the top level of
the call stack is reached. If no matching catch block is found, the default
exception handler prints a stack trace and terminates the program.
stack unwinding
• During stack unwinding, any resources that were acquired by the
method that threw the exception must be released. This is typically
done in a finally block that is executed before the exception is
propagated up the call stack. The finally block ensures that resources
are released even if an exception is thrown.
Error: / by zero

finally block executed


Error: / by zero
stack unwinding
• If the exception is thrown in the divide method, the method catches the
exception, prints an error message, and rethrows the exception. This causes
the exception to be propagated up the call stack to the main method.
• During stack unwinding, the finally block in the divide method is executed
before the exception is propagated up the call stack. In this case, the finally
block prints a message to the console.
• Finally, the main method catches the exception, prints an error message,
and the program terminates.
• This example demonstrates how stack unwinding works in Java exception
handling and how the finally block can be used to release resources.
precondition , postcondition
• A precondition must be true when a method is invoked. Preconditions
describe constraints on method parameters and any other expectations
the method has about the current state of a program just before it
begins executing.
• A postcondition is true after the method successfully returns.
Postconditions describe constraints on the return value and any other
side effects the method may have. When defining a method, you
should document all postconditions so that others know what to expect
when they call your method, and you should make certain that your
method honors all its postconditions if its preconditions are indeed
met.
assertions
• When implementing and debugging a class, it’s sometimes useful to
state conditions that should be true at a particular point in a method.
These conditions, called assertions, help ensure a program’s validity
by catching potential bugs and identifying possible logic errors during
development.
• Preconditions and postconditions are two types of assertions.
• Java includes two versions of the assert statement for validating
assertions programatically. The assert statement evaluates a boolean
expression and, if false, throws an AssertionError (a subclass of Error).
• Rules:
1. assert expression;
2. assert expression1 : expression2;
-> which evaluates expression1 and throws an AssertionError with
expression2 as the error message if expression1 is false.
• You must explicitly enable assertions when executing a program,
because they reduce performance and are unnecessary for the
program’s user.
• Run program with assertion in cmd - java -ea AssertTest
Java: String Class
chapter 16
Constructors
String methods
• length() - return the length of a String,
• charAt() - obtain the character at a specific location in a String,
• getChars() - retrieve a set of characters from a String as a char array,
• Next we have comparison methods.
• When primitive-type values are compared with ==, the result is true if
both values are identical. int a = 4, b = 4; (a==4) is true.
• When references are compared with ==, the result is true if both
references refer to the same object in memory. Example:
String s1 = new String(”Hello”);
• (s1 == “hello”) is false. because they don’t t refer to same object.
• To compare the actual contents (or state information) of objects for
equality, a method must be invoked. In the case of Strings, that method is
equals. Example:
s1.equals(“hello”) is true.
• startsWith and endsWith checks whether string startsWith and
endsWith certain characters.
concat
• // string concatination
• String s1 = new String("Happy");
• String s2 = new String(" birthday");
• String s3 = s1.concat(s2);
Extract substring
• Class String provides static methods valueOf() that take an argument
of any type and convert it to a String object.
• char[] chars = {'a','b','c','d','\n','X','X','X'};
• String s4 = String.valueOf(chars);
• System.out.println(s4); //abcd XXX
• double d = 55421.44514211231;
• s4 = String.valueOf(d);
• System.out.println(s4); // 55421.44514211231
StringBuilder class
• The features of class StringBuilder for creating and manipulating
dynamic string information—that is, modifiable strings.
• Every StringBuilder is capable of storing a number of characters
specified by its capacity. If a StringBuilder’s capacity is exceeded, the
capacity expands to accommodate the additional characters.
• In programs that frequently perform string concatenation, or other
string modifications, it’s often more efficient to implement the
modifications with class StringBuilder.
StringBuilder length, setLength, capacity and
ensureCapacity methods.
• Dynamically increasing the capacity of a StringBuilder can take a
relatively long time. Executing a large number of these operations can
degrade the performance of an application.
• If a StringBuilder is going to increase greatly in size, possibly multiple
times, setting its capacity high at the beginning will increase
performance.
• Class StringBuilder provides overloaded append methods (Fig. 16.13)
to allow values of various types to be appended to the end of a
StringBuilder.
• Works for primitive types, and for character arrays, Strings, Objects,
and more.
• ‘+’ dont work in StringBuilder. Use append().
regular expression
• A regular expression is a String that describes a search pattern for
matching characters in other Strings.
• Such expressions are useful for validating input and ensuring that data
is in a particular format.
• See codes from
JavaTestLearnShit project’s StringTest package

You might also like