m4 Notes
m4 Notes
● Definition: An exception is an abnormal condition or runtime error that occurs during code
execution.
● finally: Contains code that executes after the try/catch, regardless of whether an
exception occurred.
● Process:
● Use the throw keyword to manually trigger an exception, and specify it in the
method's throws clause if it is thrown from within a method.
● Finally block ensures that specific code executes after the try/catch blocks complete
● Exception Types
● ❑ All exception types are subclasses of the built-in class Throwable.
● ❑ Thus, Throwable is at the top of the exception class hierarchy.
● ❑ Immediately below Throwable are two subclasses that partition
● exceptions into two distinct branches.
● ❑ One branch is headed by Exception.
● ❑ This class is used for exceptional conditions that user programs
● should catch. This is also the class that you will subclass to create
● your own custom exception types.
● ❑ There is an important subclass of Exception, called RuntimeException.
● ❑ Exceptions of this type are automatically defined for the programs
● that you write and include things such as division by zero and invalid
● array indexing.
● ❑ The other branch is topped by Error, which defines exceptions that
● are not expected to be caught under normal circumstances by your
● program.
● ❑ Exceptions of type Error are used by the Java run-time system to
Throw Exceptions in Java
● Explicit Throwing: You can explicitly throw exceptions using the throw statement.
● Syntax: throw ThrowableInstance;
● ThrowableInstance must be an object of type Throwable or its subclass.
● Restrictions:
● Primitive types (e.g., int, char) and non-Throwable classes (e.g., String, Object)
cannot be used as exceptions.
● Creating Throwable Objects:
● Obtain a Throwable object from a catch clause parameter or create one using
the new operator.
● Execution Flow:
● Execution stops immediately after the throw statement; subsequent statements are
not executed.
● The nearest enclosing try block is checked for a matching catch statement.
● If no match is found, the next enclosing try block is inspected.
● If still unmatched, the default exception handler halts the program and prints the
stack trace.
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch (NullPointerException e) {
System.out.println("Caught inside demopoc.");
throw e;
}}
public static void main(String args[]) {
try {
demoproc();
} catch (NullPointerException e) {
System.out.println("Recaught: " + e);
}}
Throws in Java
● Purpose: A method must specify if it can throw an exception it does not handle, allowing
callers to manage that exception.
● Implementation: Use a throws clause in the method declaration.
● Content: The throws clause lists the types of exceptions the method may throw, except
for Error, RuntimeException, and their subclasses.
● Requirement: All other exceptions must be declared; failing to do so results in a compile-
time error.
class ThrowsDemo {
static void throwOne()
throws IllegalAccessException {
System.out.println("Inside throwOne.");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
throwOne();
} catch (IllegalAccessException e) {
System.out.println("Caught 11 + e);
}}}
Finally in Java
● Execution: The finally block runs after a try/catch block, regardless of whether an exception
was thrown.
● Behavior:
● Executes even if no matching catch statement is found for an exception.
● Runs before a method returns, whether due to an uncaught exception or an explicit
return.
● Use Case: Ideal for closing resources (e.g., file handles) and cleaning up before returning.
● Optional: The finally block is not mandatory in a try/catch structure.
static void procc() {
try {
System.out.println("inside procC");
} finally { System.out.println("procC's finally");}
}
public static void main(String args[]) {
try {
procA();
} catch (Exception e) {
System.out.println("Exception caught");
}
procB();
procc();
}
Nested Try Statements in Java
● Nesting: A try statement can be placed inside another try block.
● Exception Context: Each entry into a try statement pushes its exception context onto the
stack.
● Exception Handling:
● If an inner try lacks a matching catch, the stack unwinds to the outer try statements
to find a match.
● This process continues until a match is found or all nested try statements are
exhausted.
● Default Handling: If no catch matches, the Java runtime system handles the exception.
class NestTry { public static void main(String args[])
try { int a = args.length;
int b 42 / a;
System.out.println("a = + a);
try {
if (a==1) a = a/(a-a);
if (a==2) {
int c[] = { 1 };
c [42] = 99;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: 11 + e);
}
} catch (ArithmeticException e) {
System.out.println("Divide by 0: + e);
}}
Creating Custom Exception Subclasses in Java
● Inheritance: Custom exceptions inherit methods from the Throwable class,
as Exception does not define its own methods.
● Method Availability: All exceptions, including custom ones, have access
to Throwable methods and can override them if needed.
● Constructors: The Exception class provides four public constructors:
● Two for supporting chained exceptions.
● One creates an exception without a description.
● One allows specifying a description for the exception.
class MyException extends Exception {
private int detail;
MyException (int a) {
detail = a;
}
public String toString() {
return "MyException [" + detail + "]";
}}
class ExceptionDemo {
static void compute (int a) throws MyException {
System.out.println("Called compute(" + a + ")"); if (a > 10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute (1);
compute (20);
} catch (MyException e) {
System.out.println("Caught + e);
}}
Chained Exceptions in Java
● Introduction: Chained exceptions were introduced in JDK 1.4 to enhance the exception
handling mechanism.
● Functionality: Allows associating one exception with another, providing context for the first
exception.
● Cause Description: The second exception explains the underlying cause of the first
exception.
● Example:
● An ArithmeticException (e.g., division by zero) may occur due to an earlier I/O error
that improperly set the divisor.
● Chained exceptions enable the caller to understand both the direct error and its root
cause.
● Use Case: Useful for managing complex error situations with multiple layers of exceptions.
● class ChainExcDemo {
static void demoproc() {
NullPointerException e = new NullPointerException("top layer");
e.initCause (new ArithmeticException("cause"));
throw e;
}
public static void main(String args[]) {
try {
demoproc();
} catch (NullPointerException e{ System.out.println("Caught: + e);
System.out.println("Original cause: " + e.getCause());
}}}
Java Built-in Exceptions
Java has a range of built-in exceptions categorized into checked exceptions, unchecked
exceptions, and errors.
1. Checked Exceptions
● Definition: Checked at compile-time; must be caught or declared with throws.
● Examples:
● IOException: Input/output operation failure.
● SQLException: Error accessing a database.
● ClassNotFoundException: Class definition not found at runtime.
2. Unchecked Exceptions
● Definition: Not checked at compile-time; subclasses of RuntimeException.
● Examples:
● NullPointerException: Using null where an object is required.
● ArrayIndexOutOfBoundsException: Illegal index access in an array.
● ArithmeticException: Exceptional arithmetic condition (e.g., division by zero).
● ClassCastException: Invalid cast attempted.
3. Error
● Definition: Serious problems not meant to be caught; subclasses of Error.
● Examples:
● StackOverflowError: Occurs due to deep or infinite recursion.
● OutOfMemoryError: JVM cannot allocate memory for an object.
● Defining a Package
● ❑ A set of classes and interfaces grouped together are known as
● Packages in JAVA.
● ❑ To create a package is quite easy: simply include a package
● command as the first statement in a Java source file.
● ❑ Any classes declared within that file will belong to the specified
● package.
● ❑ The package statement defines a name space in which classes are
stored.
● Importing Packages.
● ❑ Java includes the import statement to bring certain classes, or entire
● packages, into visibility.
● ❑ Once imported, a class can be referred to directly, using only its name.
● ❑ The import statement is a convenience to the programmer and is not
● technically needed to write a complete Java program.
● ❑ If you are going to refer to a few dozen classes in your application,
● however, the import statement will save a lot of typing.
● ❑ In a Java source file, import statements occur immediately following the
● package statement (if it exists) and before any class definitions.
● ❑ This is the general form of the import statement:
Import pkg1[.pkg2].(classname|*);
● Ex
package MyPack;
public class Balance {
String name;
double bal;
public Balance (String n, double b) {
name = n;
bal = b;
}
public void show() {
if (bal<0)
System.out.print("-->");
System.out.println(name + ": $" + bal); }
}
Packages and Member Access
❑ Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods.
❑ Packages act as containers for classes and other subordinate packages.
❑ Classes act as containers for data and code.
❑ The class is Java’s smallest unit of abstraction. Because of the
interplay between classes and packages, Java addresses four categories
of visibility for class members: