0% found this document useful (0 votes)
10 views31 pages

L30 Checked, Unchecked Exceptions

The document explains the differences between checked and unchecked exceptions in Java. Checked exceptions are verified at compile time and must be handled or declared, while unchecked exceptions occur at runtime and are typically the result of programming errors. It also includes examples of both types of exceptions and discusses user-defined exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views31 pages

L30 Checked, Unchecked Exceptions

The document explains the differences between checked and unchecked exceptions in Java. Checked exceptions are verified at compile time and must be handled or declared, while unchecked exceptions occur at runtime and are typically the result of programming errors. It also includes examples of both types of exceptions and discusses user-defined exceptions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Checked and

Unchecked
Exceptions
Checked Exception

 Checked exceptions are exceptions that are checked at compile


time.
 If your code can potentially throw a checked exception, the
compiler forces you to either handle it using a try-catch block or
declare it in the method signature using the throws keyword.

2
Characteristics of Checked
Exceptions
 They are exceptions that are checked at compile time by the Java
compiler.
 They are usually exceptions that occur due to external conditions,
such as trying to open a file that does not exist or attempting to
access a database that is down.
 Examples: IOException, SQLException, FileNotFoundException,
ClassNotFoundException, etc.

3
Handling Checked Exceptions

You must handle a checked exception either by:


 Using a try-catch block to catch and handle the exception.
 Using the throws keyword in the method signature to declare that
the method may throw the exception.

4
Example

import java.io.*;

public class CheckedExceptionExample {


public static void main(String[] args) {
try {
// This code can throw an IOException, which is a checked
exception
FileReader file = new FileReader("nonexistentfile.txt");
BufferedReader fileInput = new BufferedReader(file);
System.out.println(fileInput.readLine());
fileInput.close();
} catch (IOException e) {
// Handle the checked exception
System.out.println("An IOException occurred: " + e.getMessage());
}
}
}
5
Unchecked Exception

 Unchecked exceptions are exceptions that are not checked at


compile time.
 These are typically runtime exceptions that occur during the
execution of the program, and they are typically the result of
programming errors, such as logic mistakes or invalid data.

6
Characteristics of Unchecked
Exceptions:
 They are exceptions that are not checked at compile time.
 These exceptions typically represent programming errors.
 Unchecked exceptions are subclasses of RuntimeException or
Error.
 They don't need to be declared or caught explicitly in the code.
 If you don't handle them, the program will terminate with the
exception.
 Examples: NullPointerException,
ArrayIndexOutOfBoundsException, ArithmeticException,
ClassCastException, IllegalArgumentException, etc.
7
Example

public class UncheckedExceptionExample {


public static void main(String[] args) {
int[] arr = new int[5];
try {
// This will throw an ArrayIndexOutOfBoundsException (unchecked
exception)
arr[10] = 100;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("An unchecked exception occurred: " +
e.getMessage());
}
}
}
8
9
10
Java’s Built-in Exceptions
Checked vs Unchecked Exceptions

Checked Exception:

• Exception that are checked by compiler whether programmer is


handling or not such type of exceptions are called checked exception.

• If some code within a method throws a checked exception, then the


method must either handle the exception or it must specify the
exception using throws keyword.

• In the case of checked exception compiler will check whether we are


handling exception or not.
Checked vs Unchecked Exceptions

Checked Exception:

• Consider the program to read and prints first three lines of it.

• The program doesn’t compile, because FileReader() throws a


checked exception FileNotFoundException.

• It also uses readLine() and close() methods, and these methods also
throw checked exception IOException
import java.io.*;
class prg
{
public static void main(String[] args)
{
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines.


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
• To fix the program:
 we either need to specify list of exceptions using throws, or
 need to use try-catch block.
import java.io.*;
class prg
{
public static void main(String[] args)
{
try
{
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines.


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
catch(Exception e) { }
}
}
import java.io.*;
class prg
{
public static void main(String[] args) throws IOException
{
FileReader file = new FileReader("C:\\test\\a.txt");
BufferedReader fileInput = new BufferedReader(file);

// Print first 3 lines.


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

fileInput.close();
}
}
Unchecked Exceptions
• Exceptions that are not checked at compiled time.

• In C++, all exceptions are unchecked.

• It is up to the programmers to be civilized, and specify or catch


the exceptions.

In Java exceptions under Error and RuntimeException classes


are unchecked exceptions, everything else under throwable is
checked.
 Below program compiles fine, but
throws ArithmeticException when run.

 Compiler allows it to compile, because ArithmeticException is an


unchecked exception.

class program
{
public static void main(String args[])
{
int x = 0;
int y = 10;
int z = y/x;
}
}
Unchecked Exceptions
Throwable

Exception Error

RunTime Exception IOException

ArithmeticException FileNotFoundException

ArrayIndexOutOfBoundsException
EOFException
NullPointerException
NumberFormatException
Unchecked Exceptions
 Runtime exception and its child class, Error and its
child classes are unchecked exception.

 Except this remaining are checked exceptions.


Fully Checked vs partially Checked
Exceptions
 A checked exception is said to be fully checked if and only if all
its child classes also checked.
 Ex: IOException

 A checked exception is said to be partially checked if and only if


some of its child classes are unchecked.
 Ex : Exception
Exception Partially checked exception

……..
Fully checked exception
RunTime Exception IOException
FileNotFoundException
ArithmeticException
EOFException
ArrayIndexOutOfBoundsException

NullPointerException
NumberFormatException
Create a user defined exception InvalidRegistrationNumber.
Write a java program to check whether the entered registration number
is valid or not.
If not throw an exception of type InvalidRegistrationNumber.

Valid registration numbers are 220953001 to 220953180

Ex: i/p regno =“220953050”


0/p valid registration number.

Ex: i/p regno =“170953055”


0/p invalid registration number : 170953050
// Step 1: Define the user-defined exception class
class InvalidRegistrationNumber extends Exception {
// Constructor that accepts a message
public InvalidRegistrationNumber(String message) {
super(message);
}
}

// Step 2: Write the main class


import java.util.Scanner;

public class RegistrationValidation {

// Method to check if registration number is valid


static void validateRegistrationNumber(int registrationNumber) throws
InvalidRegistrationNumber {
// Check if the registration number is within the valid range
if (registrationNumber < 220953001 || registrationNumber > 220953180) {
throw new InvalidRegistrationNumber("Invalid Registration Number: " +
registrationNumber);
}
} 27
public static void main(String[] args) {
// Step 3: Input the registration number
Scanner scanner = new Scanner(System.in);
System.out.print("Enter registration number: ");
int registrationNumber = scanner.nextInt(); // Take input from the user

try {
// Step 4: Validate the registration number
validateRegistrationNumber(registrationNumber);
System.out.println("Registration number is valid.");
} catch (InvalidRegistrationNumber e) {
// Step 5: Handle the exception
System.out.println(e.getMessage());
} finally {
scanner.close();
}
}
}

28
Tutorial

Create an Array of 4 Product objects, where Product class contains the members:
productId, productName and productType with appropriate constructors and
methods.

If product type begins with string “prod”, then print the product details otherwise
throw an user exception of type InvalidProductTypeException, which prints the
message "Invalid Product Type Exception" along with the product type.

Use exception handling technique to catch and print the error object.
Tutorial

Write a java program to read 5 subject marks from the keyboard and store only
valid values in an array. If the number entered is negative throw user defined
exception called “NegativeNumberException”. The main java program
performing the work of reading and storing values into array.
Write a java program to read 5 subject marks from the keyboard and store only
valid values in an array. If the number entered is negative throw user defined
exception called “NegativeNumberException”. If the number entered is positive
and out of the range <0-100>, throw user defined exception called
“OutOfRangeException”. The main java program performing the work of
reading and storing values into array.

You might also like