0% found this document useful (0 votes)
33 views13 pages

Chapter 6 - Oops

The document discusses exception handling in Java including built-in exception types like ArithmeticException and NullPointerException. It covers finally blocks, rethrowing exceptions, chained exceptions, and defining custom exception classes by extending the Exception class.

Uploaded by

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

Chapter 6 - Oops

The document discusses exception handling in Java including built-in exception types like ArithmeticException and NullPointerException. It covers finally blocks, rethrowing exceptions, chained exceptions, and defining custom exception classes by extending the Exception class.

Uploaded by

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

Faculty of Engineering (Degree)

Semester – 4 th
Subject Name - Object Oriented Programming – 1
Subject Code - BE103404
Faculty Name – Radhika Gokani
Chapter – 6
Exception Handling, I/O, abstract classes and interfaces
6.1 Exception types

Certainly! In Java, there are several built-in exception types that relate to various class
libraries. Let’s explore some of the most important ones:
1. ArithmeticException:
o Thrown when an exceptional condition occurs during an arithmetic operation (e.g., division by zero).
o Example:

Java

int a = 30, b = 0;
int c = a / b; // Throws ArithmeticException: Can't divide a number by 0
2. ArrayIndexOutOfBoundsException:
o Raised when an array is accessed with an illegal index (negative or greater than the array size).
o Example:

Java

int[] arr = new int[5];


int value = arr[10]; // Throws ArrayIndexOutOfBoundsException
3. ClassNotFoundException:
o Occurs when trying to access a class whose definition is not found.
o Example:

Java

try {
Class.forName("NonExistentClass");
} catch (ClassNotFoundException e) {
System.out.println("Class not found");
}
4. FileNotFoundException:
o Thrown when a file is not accessible or fails to open.
o Example:

try {
FileReader fileReader = new FileReader("nonexistent.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
5. NullPointerException:
o Raised when referring to members of a null object.
o Example:

String str = null;


char firstChar = str.charAt(0); // Throws NullPointerException
6. NumberFormatException:
o Occurs when a method cannot convert a string into a numeric format.
o Example:

String invalidNumber = "abc";


int num = Integer.parseInt(invalidNumber); // Throws NumberFormatException
7. RuntimeException:
o Represents exceptions that occur during runtime (unchecked exceptions).
o Examples include IllegalArgumentException, IllegalStateException, and others.

Remember that checked exceptions (like IOException) must be explicitly handled, while
unchecked exceptions (like NullPointerException) do not require explicit handling.

6.2 finally clause

The finally clause in Java is a powerful construct that allows you to execute code
regardless of whether an exception occurs or not. Let’s learn it into the details:
1. Purpose of finally block:
o The finally block is used to execute important code, such as closing connections,
releasing resources, or performing cleanup tasks.
o It ensures that specific statements are executed no matter what happens in the
preceding try block or any associated catch blocks.
2. Execution Flow:
o The finally block follows either a try block or a catch block.
o Whether an exception occurs or not, the statements inside the finally block always
execute.
o Even if an unhandled exception terminates the program, the finally block still runs
before the program exits.
o
3. Examples: When an exception does not occur:

class TestFinallyBlock {
public static void main(String[] args) {
try {
// Code that does not throw any exception
int data = 25 / 5;
System.out.println(data);
} catch (NullPointerException e) {
// Catch block won't be executed
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("Rest of the code...");
}
}
Output:
5
finally block is always executed
Rest of the code...

6.3 Rethrowing Exceptions


When an exception is caught in a try block, you have the option to rethrow it using
the throw keyword. This process is known as rethrowing an exception. Let me explain how
it works:

Handling Exceptions and Rethrowing:

o Normally, a catch block is used to handle exceptions raised in the try block.
o However, if the catch block is unable to handle the exception, you can rethrow it using
the throw keyword.
o When you rethrow an exception, it propagates to the exception handlers in the next higher
context (e.g., an outer try block).
o Any further catch clauses for the same try block are still ignored.

Sample Example:
public class Main
{
public int test(int n1, int n2) {
try {
return n1 / n2;
} catch (ArithmeticException e) {
throw e; // Rethrow the caught exception
}
}

public static void main(String[] args) {


Main main = new Main();
try {
System.out.println(main.test(30, 0));
} catch (Exception e) {
e.printStackTrace();
}
}
}

o In this example, the test method attempts to divide n1 by n2.


o If an ArithmeticException occurs (e.g., division by zero), it is caught in the catch block.
o The same exception is then rethrown using throw e;
o The exception propagates to the main method’s catch block, where it is handled and
printed.

6.4 chained exceptions:

In Java, chained exceptions allow you to associate one exception with another,
making debugging easier by providing additional information about the specific
error.

1. What Are Chained Exceptions?


o A chained exception occurs when you wrap an existing exception inside a new exception. The
new exception becomes the root cause of the chain.
o The original exception contains the actual error message and stack trace, while the new
exception can provide additional context.
o Chained exceptions are especially useful when an exception is thrown due to another
exception.
2. How to Create Chained Exceptions:
o You can create a chained exception using the constructors of the Throwable class.
o Two relevant constructors:
 Throwable(Throwable cause): Creates a new exception object with a specified cause
exception.
 Throwable(String desc, Throwable cause): Creates a new Throwable object with a
message and a cause.
o Methods for handling chained exceptions:
 getCause(): Returns the cause of the current exception, allowing access to the triggering
exception.
 initCause(): Sets the cause for the calling exception.
3. Example:
public class ChainedExceptionExample {
public static void main(String[] args) {
try {
String s = null;
int num = Integer.parseInt(s); // This line will throw a
NumberFormatException
} catch (NumberFormatException e) {
// Create a new RuntimeException with the message "Exception."
RuntimeException ex = new RuntimeException("Exception");
// Set the cause of the new Exception to a new
NullPointerException
// with the message "It is the actual cause of the exception."
ex.initCause(new NullPointerException("It is the actual cause
of the exception"));
// Throw the new Exception with the chained Exception
throw ex;
}
}
}

o In this example:
 A NumberFormatException is caught.
 We create a new RuntimeException with the message “Exception.”
 The cause of the new exception is set to a NullPointerException with the message “It is
the actual cause of the exception.”
 The new exception is thrown, preserving the chain.

6.5 Defining custom exception classes

In Java, you can create your own custom exceptions by extending


the Exception class. These user-defined exceptions allow you to tailor exception
handling to specific scenarios.

use custom exceptions:


1. Creating a Custom Exception:
o To create a custom exception, follow these steps:
 Inherit from the Exception class (or one of its subclasses) to create your custom exception
class.
 Define your custom exception by adding any additional behavior or properties you need.
 Optionally, provide constructors that allow you to set custom error messages or other
relevant information.
2. Example: Custom Exception for Invalid File Names: Let’s say you want to create a
custom exception to handle invalid file names. Here’s how you can do it:

Java

public class WrongFileNameException extends Exception {


public WrongFileNameException(String errorMessage) {
super(errorMessage);
}
}
In this example:

o WrongFileNameException extends the Exception class.


o The constructor takes a string argument ( errorMessage) that sets the error message for the
exception.
3. Using the Custom Exception: Now let’s use our custom exception in a sample
program:
public class TestCustomException {
static void validateFileName(String fileName) throws
WrongFileNameException {
if (!fileName.matches("[a-zA-Z0-9_]+\\.txt")) {
throw new WrongFileNameException("Invalid file name: " +
fileName);
}
}

public static void main(String[] args) {


try {
validateFileName("my_file.txt");
System.out.println("File name is valid.");
} catch (WrongFileNameException ex) {
System.out.println("Caught the exception: " + ex.getMessage());
}
}
}

o In this example:
 The validateFileName method checks if the given file name matches the pattern [a-zA-
Z0-9_]+\\.txt.
 If the file name is invalid, it throws a WrongFileNameException.
 The main method catches the exception and prints the error message.

Output:
File name is valid.

6.6 file class and its input and output

Let’s explore the Java File class, which is an essential part of handling file input and
output operations. The File class provides an abstract representation of file and
directory pathnames. Here are the key points about the File class:
1. Overview:
o The File class allows you to work with both files and directories.
o It represents system-independent views of hierarchical pathnames.
o You can create, delete, rename, and list files and directories using its methods.
2. Creating a File Instance:
o You can create a File instance using various constructors:
 File(String pathname): Creates a new File instance from a pathname string.
 File(File parent, String child): Creates a new File instance from a parent
abstract pathname and a child pathname string.
 File(URI uri): Creates a new File instance from a file URI.
 And more…
3. Common Methods:
o Some useful methods provided by the File class:
 getName(): Returns the name of the file or directory.
 getParent(): Returns the parent pathname string.
 isDirectory(): Checks if the path denotes a directory.
 isFile(): Checks if the path denotes a normal file.
 listFiles(): Returns an array of abstract pathnames for files in a directory.
 toPath(): Converts the File to a java.nio.file.Path object.
 And more…
4. Example: Listing Files in a Directory:
import java.io.File;

public class FileExample {


public static void main(String[] args) {
File directory = new File("/path/to/directory");
if (directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
System.out.println(file.getName());
}
}
}
}
}

o In this example, replace /path/to/directory with the actual directory path.


o It lists all files and subdirectories within the specified directory.

Note on Java NIO:

o The java.nio.file package provides more advanced features for file I/O.
o Consider using it for better performance and additional capabilities.

6.7 Reading data from web

In Java, you can access data from a specific URL using


the URL and URLConnection classes. Let’s explore how to achieve this:
1. Using the URL Class:
o The URL class represents a Uniform Resource Locator, which is a pointer to web content on
the World Wide Web.
o You can create a URL instance by providing the URL string.
o Here’s an example of using the URL class to extract information from a URL:

import java.net.*;
public class URLExample {
public static void main(String[] args) {
try {
URL url = new URL("https://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: " + url.getProtocol());
System.out.println("Host Name: " + url.getHost());
System.out.println("Port Number: " + url.getPort());
System.out.println("File Name: " + url.getFile());
} catch (Exception e) {
System.out.println(e);
}
}
}

o Output:
o Protocol: https
o Host Name: www.javatpoint.com
o Port Number: -1
o File Name: /java-tutorial
2. Using the URLConnection Class:
o The URLConnection class establishes a connection between your application and a resource
(such as a URL).
o You can use it to read or write data from/to the specified resource.
o To get a URLConnection object, call the openConnection() method on a URL object.
o example of reading data from a URL:

import java.io.*;
import java.net.*;

public class URLReader {


public static void main(String[] args) {
try {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();

// Read data from the URL


InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
} catch (IOException e) {
System.out.println("Error reading data: " + e.getMessage());
}
}
}

o Replace "https://www.example.com" with the actual URL you want to read from.
o This example reads the content from the specified URL and prints it line by line.

6.8 Abstract classes

In Java, abstract classes play a crucial role in designing class hierarchies and
providing a blueprint for other classes.
1. What is an Abstract Class?
o An abstract class is a class that cannot be instantiated directly (i.e., you cannot create
objects of it).
o It serves as a blueprint for other classes by defining common properties and methods.
o Abstract classes can have both abstract methods (methods without a body) and non-
abstract methods (methods with implementations).
2. Key Points about Abstract Classes:
o Declaration: You define an abstract class using the abstract keyword in its class definition.
o Inheritance: Other classes can extend (inherit from) an abstract class.
o Abstract Methods: Abstract classes can contain abstract methods, which must be
implemented by their subclasses.
o Non-Abstract Methods: They can also have regular (non-abstract) methods with
implementations.
o Constructor: Abstract classes can have constructors.
o Instance Creation: You cannot directly create an instance of an abstract class.
3. Example: Abstract Class with Abstract Method:
abstract class Shape {
int color; // Data member

abstract void draw(); // Abstract method (no implementation)


}

o In this example, Shape is an abstract class with an abstract method draw().


o Subclasses (e.g., Circle, Rectangle) must provide an implementation for draw().
4. Example: Abstract Class with Constructor and Non-Abstract Method:
abstract class Subject {
Subject() {
System.out.println("Learning Subject");
}

abstract void syllabus(); // Abstract method


void learn() {
System.out.println("Preparing Right Now!");
}
}

o Here, Subject has a constructor, an abstract method syllabus(), and a non-abstract


method learn().
5. Using Abstract Classes:
o To use an abstract class, create a concrete subclass that extends it.
o Implement all abstract methods in the subclass.
o You can create objects of the subclass.
6. Benefits of Abstract Classes:
o Code Reusability: Abstract classes allow you to define common behavior once and reuse it
across multiple subclasses.
o Design Flexibility: They provide a way to enforce a certain structure in derived classes.

6.9 Interfaces

An interface is a powerful construct that allows you to define a blueprint for


behaviour.

What is an Interface in Java?

o An interface is an abstract type used to specify the behaviour of a class.


o It serves as a contract that defines a set of methods (with no implementation) that a class
must provide.
o Key points about interfaces:
 An interface can contain only abstract methods (methods without a body) and static
constants.
 It provides a way to achieve abstraction and multiple inheritances in Java.
 Interfaces represent the IS-A relationship (similar to class inheritance).
2. Syntax for Declaring an Interface:
o To declare an interface, use the interface keyword:

interface MyInterface {
// Declare constant fields (static and final by default)
int MY_CONSTANT = 42;

// Declare abstract methods (no method body)


void doSomething();
int calculate(int x, int y);
}

3. Implementing an Interface:
o A class can implement one or more interfaces using the implements keyword.
o When a class implements an interface, it must provide implementations for all the methods
declared in that interface.
o Example:

class MyClass implements MyInterface {


@Override
public void doSomething() {
// Implementation for doSomething()
}

@Override
public int calculate(int x, int y) {
// Implementation for calculate()
return x + y;
}
}
4. Advantages of Interfaces:
o Achieving total abstraction: Interfaces allow you to define behavior without specifying
implementation details.
o Supporting multiple inheritances: A class can implement multiple interfaces, overcoming
the limitation of single inheritance in classes.
o Promoting loose coupling: Interfaces help decouple classes by defining contracts without
enforcing a specific class hierarchy.
5. Difference Between Class and Interface:
o Class:
 Can be instantiated (objects can be created).
 Can contain concrete (implemented) methods.
 Supports access specifiers (private, protected, public).
o Interface:
 Cannot be instantiated (no objects).
 Contains only abstract methods (no implementation).
 All methods are implicitly public.
 Can extend other interfaces (but not classes).
6. Example: Using an Interface:

Java

interface Player {
int MAX_SCORE = 100; // Constant field

void play(); // Abstract method


void pause();
}

class VideoPlayer implements Player {


@Override
public void play() {
// Implementation for play()
}

@Override
public void pause() {
// Implementation for pause()
}
}

6.10 Comparable and Cloneable interface


Comparable Interface:
The Comparable interface is used to compare objects of the same class based on a
natural ordering. When a class implements Comparable, it provides a way to define
how instances of that class should be compared.
Purpose:

o The Comparable interface allows you to define the default ordering for objects of your class.
o It provides the compareTo method, which compares the current object with another object.
2. Method Signature:

int compareTo(T other);

o The compareTo method returns:


 A negative integer if the current object is less than the specified object ( other).
 Zero if the current object is equal to the specified object.
 A positive integer if the current object is greater than the specified object.
3. Example: Suppose we have a Person class with a name field. We can make instances
of Person comparable based on their names:
class Person implements Comparable<Person> {
private String name;

public Person(String name) {


this.name = name;
}

@Override
public int compareTo(Person other) {
return this.name.compareTo(other.name);
}
}
4. Usage:
o You can use Comparable when sorting collections (e.g., List, Set) of objects.
o Collections that support natural ordering (e.g., TreeSet, Arrays.sort) use
the compareTo method.
Cloneable Interface:
The Cloneable interface is a marker interface in Java. It indicates that a class can be
cloned using the Object.clone() method.
Purpose:

o The Cloneable interface allows you to create a copy (clone) of an object.


o By convention, a class implementing Cloneable should override Object.clone() to
provide a public clone method.
2. Method Signature:
o The Object.clone() method is protected and returns a shallow copy of the object.
o To create a deep copy, you need to override clone() and handle copying of internal fields.
3. Example: Suppose we have a Point class representing a 2D point. We can make it
cloneable:
class Point implements Cloneable {
private int x;
private int y;

public Point(int x, int y) {


this.x = x;
this.y = y;
}

@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
4. Usage:
o Use Cloneable when you want to create a copy of an object without explicitly using
the new operator.
o Remember that clone() performs a shallow copy by default; for deep copies, customize the
method.

You might also like