0% found this document useful (0 votes)
7 views15 pages

Unit 4 Ans

An exception is an unexpected event during program execution that disrupts the normal flow, often due to errors like invalid input or division by zero. The document explains the use of try, catch, and finally blocks for handling exceptions in Java, along with user-defined exceptions like NoMatchException. It also covers runtime exceptions, streams in Java, and methods for InputStream and OutputStream classes for data handling.

Uploaded by

Sanika Deshmukh
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)
7 views15 pages

Unit 4 Ans

An exception is an unexpected event during program execution that disrupts the normal flow, often due to errors like invalid input or division by zero. The document explains the use of try, catch, and finally blocks for handling exceptions in Java, along with user-defined exceptions like NoMatchException. It also covers runtime exceptions, streams in Java, and methods for InputStream and OutputStream classes for data handling.

Uploaded by

Sanika Deshmukh
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

What is an Exception?

An exception is an unexpected or abnormal event that occurs during the execution of a program and
disrupts the normal flow of instructions. Exceptions occur due to errors such as invalid user input,
division by zero, accessing an invalid memory location, file not found, or network issues.

try block

A try block is used to enclose the code that may cause an exception.
If an exception occurs inside the try block, the control is transferred to the corresponding catch block.

Syntax:

try {
// code that may generate an exception
}

catch block

A catch block is used to handle the exception that occurs in the try block.
It must be followed immediately after the try block and specifies the type of exception it can handle.

Syntax:

catch (ExceptionType e) {
// code to handle the exception
}

Example:
try {
int a = 10 / 0;
}
catch (ArithmeticException e) {
[Link]("Division by zero error");
}

finally block

A finally block is used to execute important code whether an exception occurs or not.
It is generally used for cleanup operations such as closing files, database connections, or releasing
resources.

Syntax:

finally {
// code that always executes
}

Example:
throw keyword

The throw keyword is used to explicitly throw an exception from a method or a block of code.
It is mainly used to throw user-defined or custom exceptions.

Syntax:

throw new ExceptionType("Error message");

Example:

Note (GFG-style):

 throw is used to explicitly throw an exception


 throws is used in the method signature (often confused in exams)
throws: Declares exception in method signature

Exception caught: Not eligible to vote

Finally block executed

Program continues...
Define “No Match” Exception
A No Match Exception is a user-defined exception in Java.
It is thrown when a given string does not match the expected value, in this case "Java".
User-defined exceptions are created by extending the Exception class.

Java Program to Demonstrate “No Match” Exception


Program Explanation

 A custom exception class NoMatchException is created by extending Exception.


 The program checks whether the input string is equal to "Java".
 If the string does not match, the exception is explicitly thrown using the throw keyword.
 The exception is handled using try–catch.
Key Points (for Exams)
 NoMatchException is a user-defined exception
 throw is used to explicitly throw the exception
 throws is used in method declaration
 try–catch is used to handle the exception
 Program checks string equality using equals()

Create exception class (user defined exception), write a program to generate


and handle that exception. Give the basic and simple program in Java.

User-Defined Exception in Java


A user-defined exception is created by extending the Exception class.
It is used when we want to handle application-specific errors.
Output
File copied successfully
Runtime Exceptions in Java
Runtime exceptions are exceptions that occur during program execution.
They are unchecked exceptions, meaning they are not checked at compile time.

Scenarios Where Different Runtime Exceptions Occur


1. ArithmeticException

Scenario: Division by zero.

int a = 10 / 0;

Explanation:
Occurs when an illegal arithmetic operation is performed.

2. NullPointerException

Scenario: Accessing an object that is not initialized.

String s = null;
[Link]([Link]());

Explanation:
Occurs when a method or variable is accessed using a null reference.

3. ArrayIndexOutOfBoundsException

Scenario: Accessing an invalid array index.

int a[] = {1, 2, 3};


[Link](a[5]);

Explanation:
Occurs when the index is outside the array size.

4. NumberFormatException

Scenario: Converting an invalid string to a number.

int n = [Link]("abc");

Explanation:
Occurs when a string cannot be converted into a numeric type.

5. ClassCastException

Scenario: Invalid type casting.

Object obj = "Hello";


Integer i = (Integer) obj;

Explanation:
Occurs when an object is cast to an incompatible type.
6. StringIndexOutOfBoundsException

Scenario: Accessing an invalid index in a string.

String s = "Java";
[Link]([Link](10));

Explanation:
Occurs when an invalid character index is used.

Write a Java program that reads '.txt' file and displays contents on the
screen. Give the simple and basic Java program.
Streams in Java
What are Streams in Java?

A stream in Java is a sequence of data that flows from a source to a destination.


Streams are mainly used for input and output (I/O) operations, such as reading data from a file, keyboard,
or writing data to a file or screen.

Java provides stream classes in the [Link] package.

Types of Streams in Java


Java streams are broadly classified into two main types:

1. Byte Streams
2. Character Streams

1. Byte Streams
Definition: Byte streams are used to handle binary data (raw bytes) such as images, audio, video, or
executable files.
They read and write data one byte (8 bits) at a time.

Base Classes:
 InputStream
 OutputStream

Common Byte Stream Classes:


 FileInputStream
 FileOutputStream
 BufferedInputStream
 BufferedOutputStream

Example (Byte Stream):


Use: Suitable for non-text files.

2. Character Streams
Definition: Character streams are used to handle text data (characters).
They read and write data one character (16 bits) at a time and support Unicode.

Base Classes:
 Reader
 Writer

Common Character Stream Classes:


 FileReader
 FileWriter
 BufferedReader
 BufferedWriter

Example (Character Stream):

Use: Best for text files.

Difference Between Byte Streams and Character Streams


Byte Streams Character Streams

Handle binary data Handle text data

Read/write 8 bits Read/write 16 bits

Use InputStream / OutputStream Use Reader / Writer

No Unicode support Supports Unicode


Purpose of Streams in Java

The purpose of streams in Java is to perform input and output (I/O) operations in a simple, consistent,
and efficient way.
Streams provide a mechanism to read data from a source and write data to a destination.

Main Purposes of Streams

1. Data Input and Output


Streams allow Java programs to read data from various sources such as:
o Keyboard
o Files
o Network
and write data to:
o Screen
o Files
o Network
2. Abstraction of I/O Operations
Streams hide the complex hardware and OS-level details and provide a common interface for all
types of I/O.
3. Sequential Data Processing
Streams process data sequentially, one byte or character at a time, making data handling simple and
organized.
4. Support for Different Data Types
Java streams support:
o Byte data (images, audio, video)
o Character data (text files)
5. Platform Independence
Streams make I/O operations platform-independent, allowing the same code to run on different
systems.
6. Efficient Data Handling
With buffered streams, Java improves performance by reducing direct access to physical devices.

Methods of InputStream Class


The InputStream class is an abstract class used to read byte data from a source.

1. int read()

 Reads one byte of data at a time.


 Returns the byte value (0–255).
 Returns -1 if the end of the stream is reached.

Example:

int ch = [Link]();

2. int read(byte[] b)

 Reads bytes from the input stream and stores them into a byte array.
 Returns the number of bytes read.
Example:

byte[] b = new byte[10];


[Link](b);

3. void close()

 Closes the input stream.


 Releases system resources associated with the stream.

Example:

[Link]();

Methods of OutputStream Class


The OutputStream class is an abstract class used to write byte data to a destination.

1. void write(int b)

 Writes one byte of data to the output stream.

Example:

[Link](65); // Writes 'A'

2. void write(byte[] b)

 Writes an array of bytes to the output stream.

Example:

byte[] b = "Java".getBytes();
[Link](b);

3. void flush()

 Forces any buffered output bytes to be written to the destination.

Example:

[Link]();

You might also like