Exception
Exception
Java Exceptions
• An exception is an unexpected event that occurs during program
execution.
• It affects the f low of the program instructions which can cause the
program to terminate abnormally.
• An exception can occur for many reasons. Some of them are:
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out of disk memory)
• Code errors
• Opening an unavailable file
• The following are the sequence of events that can happen when the
program throws an exception:
• Examples:
• IOException
• SQLException
• FileNotFoundException
• Unchecked Exceptions
• Unchecked exceptions are exceptions that are not checked at
compile-time.
• They are subclasses of RuntimeException.
• Unchecked exceptions represent programming errors, such as
logic mistakes or improper use of an API.
• Examples:
• NullPointerException
• ArrayIndexOutOfBoundsException
• ArithmeticException
• Errors
• Errors are serious issues that a reasonable application should
not try to catch. They are typically conditions that a program
cannot recover from and are external to the application.
• Examples:
• OutOfMemoryError
• StackOverflowError
• VirtualMachineError
• try: Code where errors might happen.
• catch: Deals with the specific issue.
• finally: Always runs to clean up, no matter what.
• try
Exception Handling Keywords
• The try block contains code that might throw an exception. If an
exception occurs, it is thrown to the corresponding catch block.
• catch
• The catch block handles the exception thrown by the try block. Multiple
catch blocks can be used to handle different types of exceptions.
• finally
• The finally block contains code that will always execute,
regardless of whether an exception was thrown or caught. It is
typically used for resource cleanup.
• throw
• The throw keyword is used to explicitly throw an exception.
• throws
• The throws keyword is used in a method signature to declare
that the method might throw one or more exceptions.
Basic Exception Handling Example
• public class BasicExceptionHandling {
• public static void main(String[] args) {
• try {
• int result = 10 / 0; // This will throw
ArithmeticException
• } catch (ArithmeticException e) { Output:
•}
Nested try Blocks Output:
Outer try block
• public class NestedTryExample { Inner catch: Arithmetic error: / by zero
• public static void main(String[] args) { Outer catch: Array index out of bounds: Index
• try { 10 out of bounds for length 3
• System.out.println("Outer try block"); Outer finally block
• try {
• int result = 10 / 0; // This will throw ArithmeticException
• } catch (ArithmeticException e) {
• System.out.println("Inner catch: Arithmetic error: " +
e.getMessage());
• }
• int[] numbers = {1, 2, 3};
• System.out.println(numbers[10]); // This will throw
ArrayIndexOutOfBoundsException
• } catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("Outer catch: Array index out of bounds: "
+ e.getMessage());
• } finally {
• System.out.println("Outer finally block");
• }
• }
• In Java, printStackTrace() is a method of the Throwable class,
which is the superclass of all exceptions and errors.
• } catch (IOException e) {
• e.printStackTrace();
• }
• }
• }
• What is ClassNotFoundException?
• The ClassNotFoundException is a checked exception that signals the
Java Runtime Environment (JRE) cannot f ind the specif ied class in its
classpath during runtime.
• It's impor tant to note that this is different from the
NoClassDefFoundError, which occurs when the class was available
during compile-time but not at runtime.
• Common Causes
• Missing JAR: The class might be present in a JAR file that's not in the
runtime classpath.
• Misconfigured Build Tools: Build tools like Maven or Gradle might not
have properly packaged the class or included necessary dependencies.
• Dynamic Class Loading: Using reflection to load classes can cause this if
the class is not available.
• public class ClassNotFoundExceptionExample {
• try {
• Class.forName("com.javaguides.corejava.Demo");
• ClassLoader.getSystemClassLoader().loadClass("com.ja
vaguides.corejava.Demo");
• } catch (ClassNotFoundException e) {
• e.printStackTrace();
• }
• }
•}
• StringIndexOutOfBoundsException
• StringIndexOutOfBoundsException is a runtime exception
thrown when an attempt is made to access an index in the
String object that is either negative or greater than or equal to
the size of the string.
• Common Causes
• Passing Out-of-Range Values: For instance, passing a negative size
to a method expecting a positive size.