0% found this document useful (0 votes)
8 views49 pages

Exception

Java exceptions are unexpected events during program execution that can disrupt the flow of instructions, potentially causing abnormal termination. They can be categorized into checked exceptions, unchecked exceptions, and errors, with various handling mechanisms like try-catch blocks and custom exceptions. The document provides examples of exception handling, including common exceptions like ArithmeticException and FileNotFoundException, as well as the use of keywords like throw and throws.

Uploaded by

tamilpandi469
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views49 pages

Exception

Java exceptions are unexpected events during program execution that can disrupt the flow of instructions, potentially causing abnormal termination. They can be categorized into checked exceptions, unchecked exceptions, and errors, with various handling mechanisms like try-catch blocks and custom exceptions. The document provides examples of exception handling, including common exceptions like ArithmeticException and FileNotFoundException, as well as the use of keywords like throw and throws.

Uploaded by

tamilpandi469
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Java 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:

• Program stops: The program pauses where the error occurred.


• Error message: A message appears, telling you about the problem.
• Exception handling: If you’ve written code to handle exceptions (try-
except blocks), that code will run.
• No handling: If you haven’t written exception handling code, the
program will crash.
Types of Exceptions
• Checked Exceptions
• Checked exceptions are exceptions that are checked at compile
-time. These exceptions must be either caught or declared in the
method signature using the throws keyword.
• They represent conditions that a reasonable application might
want to catch.

• 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:

• System.out.println("Caught exception: " Caught exception: / by zero


+ e.getMessage()); Finally block executed.
• } finally {
• System.out.println("Finally block
executed.");
• }
• }
•}
Handling Multiple Exceptions
• public class MultipleCatchExample {
• public static void main(String[] args) {
• try {
• int[] numbers = {1, 2, 3};
• System.out.println(numbers[10]); // This will throw
ArrayIndexOutOfBoundsException
• int result = 10 / 0; // This will throw ArithmeticException
• } catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("Array index out of bounds: " +
e.getMessage());
• } catch (ArithmeticException e) {
• System.out.println("Arithmetic error: " + e.getMessage());
Output:

• } Array index out of bounds: Index 10 out of bounds for


• } length 3

•}
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.

• This method is used to print the stack trace of the throwable


object to the standard error stream (usually the console).
• The stack trace contains information about the sequence of
method calls that led to the exception being thrown.
• public class PrintStackTraceExample {
The printStackTrace() method prints the stack trace
of the exception to the console.In the example, we
• public static void main(String[] args) { deliberately cause an ArithmeticException by
dividing by zero.The catch block catches the
• try { exception and prints the stack trace.
• // Deliberately causing an exception
(division by zero) java.lang.ArithmeticException: / by zero
• int result = 10 / 0; at
PrintStackTraceExample.main(PrintStackTraceE
• } catch (ArithmeticException e) { xample.java:7)
• // Print the stack trace of the Program continues after the exception...
exception
• e.printStackTrace();
• }

• System.out.println("Program
continues after the exception...");
• }
•}
Custom Exceptions
• class InvalidAgeException extends Exception {
• public InvalidAgeException(String message) {
• super(message);
• }
• }
• public class CustomExceptionExample {
• public static void main(String[] args) {
• try {
• validateAge(15);
• } catch (InvalidAgeException e) {
• System.out.println("Caught custom exception: " +
e.getMessage());
• }
• }
• public static void validateAge(int age) throws
InvalidAgeException {
• if (age < 18) {
• throw new InvalidAgeException("Age must be 18 or
older.");
• }
• System.out.println("Age is valid.");
• }
• }
• Problem without exception handling

• Example 1 Exception in thread "main" java.lang.ArithmeticException: / by zero


• TryCatchExample1.java

• public class TryCatchExample1 {



• public static void main(String[] args) {

• int data=50/0; //may throw exception

• System.out.println("rest of the code");

• }

• }
• Solution by exception handling
• Example 2
• TryCatchExample2.java

• public class TryCatchExample2 {



• public static void main(String[] args) {
• try Output:
• { java.lang.ArithmeticException: / by zero rest of the code
• int data=50/0; //may throw exception
• }
• //handling the exception
• catch(ArithmeticException e)
• {
• System.out.println(e);
• }
• System.out.println("rest of the code");
• }

• }
Think
• public class TryCatchExample3 {

• public static void main(String[] args) {
• try
• {
• int data=50/0;
• System.out.println("rest of the code");
• }
• // handling the exception
• catch(ArithmeticException e)
• {
• System.out.println(e);
• }

• }

• }
Ans
• java.lang.ArithmeticException: / by zero
• Here, we can see that if an exception occurs in the try block, the
rest of the block code will not execute.
• public class TryCatchExample5 {

Let's see an example to print a custom message on
• public static void main(String[] args) {
exception.
• try
• {
• int data=50/0; //may throw exception
• }
Output:
• // handling the exception Can't divided by zero
• catch(Exception e)
• {
• // displaying the custom message
• System.out.println("Can't divided by zero");
• }
• }

•}
• Let's see an example to handle another unchecked
exception.
• public class TryCatchExample9 {

• public static void main(String[] args) {
• try
• {
• int arr[]= {1,3,5,7};
• System.out.println(arr[10]); //may throw exception
• }
• // handling the array exception Output:

• catch(ArrayIndexOutOfBoundsException e) java.lang.ArrayIndexOutOfBoundsException: 10 rest


of the code
• {
• System.out.println(e);
• }
• System.out.println("rest of the code");
• }

• }
• FileNotFoundException
• The FileNotFoundException is a checked exception that indicates
that a file with the specified pathname does not exist.

• Alternatively, in some scenarios, it can mean the application does


not have adequate permissions to access the file.
• import java.io.FileReader;
• import java.io.IOException;
• public class FileNotFoundExceptionExample {
• public static void main(String[] args) {
• try {
• FileReader reader = new
FileReader("non_existent_file.txt");
• int character;

• while ((character = reader.read()) != -1) {


• System.out.print((char) character);
• }
• reader.close();

• } 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 {

• public static void main(String[] args) {

• 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.

• It is a subclass of the IndexOutOfBoundsException and shares


its characteristics but is specifically tailored to handle erroneous
operations on strings.
• public class StringIndexOutOfBounds {
• public static void main(String[] args) {
• String str = "Hello World";
• try {
• char charAtNegativeIndex = str.charAt(-1); // Trying to
access at negative index
• char charAtLengthIndex = str.charAt(11); // Trying to
access at index equal to size of the string
• } catch (StringIndexOutOfBoundsException e) {
• System.err.println("StringIndexOutOfBoundsException
caught");
• e.printStackTrace();
• }
• }
•}
IllegalArgumentException
• The IllegalArgumentException is a runtime exception thrown by the
Java system (or by applications) to indicate that a method has
received an argument that is invalid or inappropriate in context.

• Common Causes
• Passing Out-of-Range Values: For instance, passing a negative size
to a method expecting a positive size.

• Inappropriate Null Arguments: Passing null to a method that


explicitly requires a non-null argument.

• Incompatible Data Types: For instance, passing a string representing


a date in the wrong format.

• Out-of-bounds Values: Providing a value outside an expected range.


• public class Person {
• private int age;

• public void setAge(int age) {


• if (age < 0) {
• throw new IllegalArgumentException("Age cannot
be negative.");
• }
• this.age = age;
• }

• public static void main(String[] args) {


• Person person = new Person();
• person.setAge(-5); // This will throw an
IllegalArgumentException
• }
• }
• What is NumberFormatException?
• NumberFormatException is a runtime exception in Java that
signals an attempt to convert a string into a number, but the string
does not have the appropriate format.

• This typically occurs when using methods like Integer.parseInt() or


Double.parseDouble() on strings that don't represent valid
numbers.
• Common Causes
• User Input: Users may input data that looks numeric but isn't valid.
For instance, "123.45.67" might appear at a glance to be a number,
but it's not a valid format.

• Data Import: When importing data from external sources, there's
always the risk of malformed data.

• Strings with Non-Numeric Characters: Attempting to parse strings
with characters that aren't valid in numbers, e.g., "12A34" o
r "12.34.56".
• public class NumberFormatExceptionExample {

• public static void main(String[] args) {

• String str1 = "100ABCD";


• try {
• int x = Integer.parseInt(str1); // Converting string with
inappropriate format
• int y = Integer.valueOf(str1);
• } catch (NumberFormatException e) {
• System.err.println("NumberFormatException caught!");
• e.printStackTrace();
• }
• }
• }
• NumberFormatException caught!
• java.lang.NumberFormatException: For input string: "100ABCD"
• at
java.base/java.lang.NumberFormatException.forInputString(Numb
erFormatException.java:68)
• at java.base/java.lang.Integer.parseInt(Integer.java:652)
• at java.base/java.lang.Integer.parseInt(Integer.java:770)
• at
NumberFormatExceptionExample.main(NumberFormatExceptionE
xample.java:7)
• ClassCastException has thrown to indicate that the code has
attempted to cast an object to a subclass of which it is not an
instance.

• This exception extends the RuntimeException class and thus,
belongs to those exceptions that can be thrown during the
operation of the Java Virtual Machine (JVM). It is an unchecked
exception and thus, it does not need to be declared in a
method’s or a constructor’s throws clause.
• public class ClassCastExceptionExample {
• public static void main(String[] args) {
• Object obj = new Integer(100);
• System.out.println((String) obj);
• }
•}
• Java throw keyword
• The Java throw keyword is used to throw an exception explicitly.

• We specify the exception object which is to be thrown. The


Exception has some message with it that provides the error
description. These exceptions may be related to user inputs,
server, etc.
Example 1: Throwing Unchecked Exception
Example 2: Throwing Checked Exception

You might also like