0% found this document useful (0 votes)
9 views

Unit_3

The document provides an overview of exception handling in Java, including built-in and user-defined exceptions, keywords for handling exceptions, and the creation of custom exceptions. It also covers multithreading concepts, including thread lifecycle, synchronization, and the distinction between daemon and non-daemon threads. Additionally, it discusses Java streams, file handling, and the File class for managing file operations.

Uploaded by

jadavm940
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)
9 views

Unit_3

The document provides an overview of exception handling in Java, including built-in and user-defined exceptions, keywords for handling exceptions, and the creation of custom exceptions. It also covers multithreading concepts, including thread lifecycle, synchronization, and the distinction between daemon and non-daemon threads. Additionally, it discusses Java streams, file handling, and the File class for managing file operations.

Uploaded by

jadavm940
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/ 16

2023 - 24

CS -19 Programming with JAVA

Bhavesh K. Hadiyal
HOD of Computer science
Department OMVVIM College
2022 - 23
Index
- Introduction to exception handling
- try, catch, finally, throw, throws
- Creating user defined Exception class
- Thread and its Life Cycle (Thread States)
- Thread Class and its methods
- Synchronization in Multiple Threads (Multithreading)
- Deamon Thread, Non-Deamon Thread
- Stream and its types (Input, Output, Character, Byte)
- File and RandomAccessFile Class
- Reading and Writing through Character
Stream Classes (FileReader, BufferedReader, FileWriter,
BufferedWriter)
- Reading and Writing through Byte Stream Classes
(InputStream, FileInputStream, DataInputStream,
OutputStream, FileOutputStream, DataOutputStream)
- StreamTokenizer Class
- Piped Streams,
- Bridge Classes: InputStreamReader and OutputStreamWriter
- ObjectInputStream, ObjectOutputStream
Exceptions in Java
Dictionary Meaning: Exception is an abnormal condition
An exception is an unexpected event that occurs during program execution.
It affects the flow of the program instructions which can cause the program to terminate
abnormally. In Java, an exception is an event that disrupts the normal flow of the program.
It is an object which is thrown at runtime.
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

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
An exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions.
 Provision to Complete Program Execution
 Easy Identification of Program Code and Error-Handling Code
 Propagation of Errors
 Meaningful Error Reporting
 Identifying Error Types
Exceptions can be categorized in two ways:
 Built-in Exceptions
 Checked Exception
 Unchecked Exception
 User-Defined Exceptions

A. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions because these
exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions.
The compiler will not check these exceptions at compile time.
In simple words, if a program throws an unchecked or run-time exception, and even if we didn’t
handle or declare it, the program would not give a compilation error.
B. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called ‘user-defined Exceptions’.
GO to index page
Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
Below is the list of important built-in exceptions in Java.
ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic
operation.
ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an
illegal index. The index is either negative or greater than or equal to the size of the array.
ClassNotFoundException: This Exception is raised when we try to access a class whose definition is
not found.
FileNotFoundException: This Exception is raised when a file is not accessible or does not open.
IOException: It is thrown when an input-output operation failed or interrupted
InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing,
and it is interrupted.
NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified
NoSuchMethodException: It is thrown when accessing a method that is not found.
NullPointerException: It is raised when referring to the members of a null object. (Null->nothing)
NumberFormatException: It is raised when method couldn’t convert string into a numeric format.
RuntimeException: This represents an exception that occurs during runtime.
StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is
either negative or greater than the size of the string
IllegalArgumentException : This exception will throw the error or error statement when the
method receives an argument which is not accurately fit to the given relation or condition. It
comes under the unchecked exception.
IllegalStateException : This exception will throw an error or error message when the method is not
accessed for the particular operation in the application. It comes under the unchecked exception.

Java Exception Keywords


Java provides five keywords that are used to handle the exception.
Keyword Description
try The "try" keyword is used to specify a block where we should place an exception
code. We can't use try block alone it must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. Which means we can't use catch
block without try. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It is always used with method signature.

Java try block


Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
If an exception occurs at the particular statement in the try block, the rest of the block code will
not execute.
So, it is recommended not to keep the code in try block that will not throw an exception.
Java try block must be followed by either catch or finally block. GO to index page
Java catch block
Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. You can use multiple catch block with a single try block.
The declared exception must be the parent class exception (i.e., Exception) or the generated
exception type. However, the good approach is to declare the generated type of exception
The catch block must be used after the try block only.

Java finally block


Java finally block is a block used to execute important code such as closing the connection, etc.
Java finally block is always executed whether an exception is handled or not.
Therefore, it contains all the necessary statements that need to be printed regardless of the
exception occurs or not.
The finally block follows the try-catch block.
Why use Java finally block?
Finally block in Java can be used to put "cleanup" code such as closing a file or connection, etc.
The important statements to be printed can be placed in the finally block.
Nested try block
In Java, using a try block inside another try block is permitted. It is called as nested try block.

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.
We can throw either checked or unchecked exceptions in Java by throw keyword.
It is mainly used to throw a custom exception.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
throw new exception_class("error message");
Let's see the example of throw IOException.
throw new IOException("sorry device error");

Java throws keyword


The Java throws keyword is used to declare an exception.
It gives an information to the programmer that there may occur an exception.
So, it is better for the programmer to provide the exception handling code so that the normal flow
of the program can be maintained.
Exception Handling is mainly used to handle the checked exceptions.
Syntax of Java throws
return_type method_name () throws exception_class_name {
//method code
}
Advantage of Java throws keyword
Now Checked Exception can be propagated (forwarded in call stack).
It provides information to the caller of the method about the exception.
GO to index page
Creating user defined Exception class
Java provides us the facility to create our own exceptions which are basically derived classes of
Exception. Creating our own Exception is known as a custom exception or user-defined exception.
Basically, Java custom exceptions are used to customize the exception according to user needs.
In simple words, we can say that a User-Defined Exception or custom exception is creating your
own exception class and throwing that exception using the ‘throw’ keyword.
Why Use Custom Exceptions?
 Although java provides the Exception class, which covers almost all cases of exceptions but
custom exceptions will bring the spotlight onto exception handling.
 Custom exceptions enable the flexibility of adding messages and methods that are not part of
the Exception class.
 They can be used to store case-specific messages like status codes and error codes or override
an existing method to present the exception as per the use case.
 Custom exceptions are helpful while writing exceptions for business logic.
 It helps the developers to better understand the exception, which is business-specific.
Example:
package javaapplication1;
public class MarksExceptionClass extends Exception{
public MarksExceptionClass(String msg) { super(msg); }
}

package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.println("Enter marks of JAVA : ");
int $m = s.nextInt();
try
{
if($m<0 || $m > 100)
throw new MarksExceptionClass("Wrong MArks.");
else
System.out.println("Marks of JAVA is : " + $m);
}
catch(MarksExceptionClass obj)
{ System.out.println("Exception caught : " + obj); }
}
}
This would produce the following result:
Enter marks of JAVA :
123
Exception caught : javaapplication1.MarksExceptionClass: Wrong MArks.
GO to index page
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Typically, we can define threads as a sub process with lightweight with the smallest unit of
processes and also has separate paths of execution. These threads use shared memory but they
act independently hence if there is an exception in threads that do not affect the working of other
threads despite them sharing the same memory.
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states. A thread lies only in
one of the shown states at any instant:
 New
 Runnable
 Blocked
 Waiting
 Timed Waiting
 Terminated
The diagram shown below represents various states of a thread at any instant in time.

GO to index page
Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
 Thread()
 Thread(String name)
 Thread(Runnable r)
 Thread(Runnable r,String name)

Commonly used methods of Thread class:


public void run(): is used to perform action for a thread.
public void start(): starts the execution of the thread.JVM calls the run() method on the thread.
public void sleep(long miliseconds): Causes the currently executing thread to sleep (temporarily
cease execution) for the specified number of milliseconds.
public void suspend(): is used to suspend the thread(depricated).
public void resume(): is used to resume the suspended thread(depricated).
public void stop(): is used to stop the thread(depricated).

Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part of such program is called a thread. So, threads
are light-weight processes within a process.
Threads can be created by using two mechanisms :
 Extending the Thread class
 Implementing the Runnable Interface
Synchronization in Java is the capability to control the access of multiple threads to any shared
resource.
Java Synchronization is better option where we want to allow only one thread to access the shared
resource.
Why use Synchronization?
The synchronization is mainly used to
 If you start with at least two threads inside a program, there might be a chance when
multiple threads attempt to get to the same resource.
 It can even create an unexpected outcome because of concurrency issues.
Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization
Process Synchronization: It means sharing system resources by processes in such a way that,
Concurrent access to shared data is handled thereby minimizing the chance of inconsistent data.
Thread Synchronization: It means that every access to data shared between threads is protected
so that when any thread starts operation on the shared data, no other thread is allowed access
until the first thread is done.
GO to index page
Daemon Thread and Non-Daemon
In Java, there are two types of threads:
 Daemon Thread
 User Thread (Non-Daemon )
Thread type is being checked (User thread or Daemon thread) by using isDaemon() method. It
returns true if it is daemon otherwise it returns false.

Daemon Thread in Java


Daemon thread in Java is a low-priority thread that runs in the background to perform tasks such
as garbage collection. Daemon thread in Java is also a service provider thread that provides
services to the user thread. Its life depends on the mercy of user threads i.e. when all the user
threads die, JVM terminates this thread automatically.
In simple words, we can say that it provides services to user threads for background supporting
tasks. It has no role in life other than to serve user threads.
Example of Daemon Thread in Java: Garbage collection in Java (gc), finalizer, etc.

Points to remember for Daemon Thread in Java


 It provides services to user threads for background supporting tasks. It has no role in life
than to serve user threads.
 Its life depends on user threads.
 It is a low priority thread.

Non-Daemon Thread in Java


User Thread or Non-Daemon are designed to do specific or complex task where as daemon threads
are used to perform supporting tasks.
What are Non-Daemon threads?
Non-daemon threads are user threads designed to do specific, complex tasks. These are high
priority threads that run in the foreground. They are often referred to as “normal threads” that
we see and use in day to day coding. Also, any thread created from the Main thread is a non-
daemon/user thread. Non daemon / user threads are created usually by the Java application.

User Thread Daemon Thread


JVM wait until user threads to finish their The JVM will not wait for daemon threads to
work. It never exit until all user threads finish their work. The JVM will exit as soon as all
finish their work. user threads finish their work.
JVM will not force to user threads for If all user threads have finished their work JVM
terminating, so JVM will wait for user will force the daemon threads to terminate
threads to terminate themselves.
User threads are created by the application. Mostly Daemon threads created by the JVM.
Mainly user threads are designed to do Daemon threads are design as to support the
some specific task. user threads.
User threads are foreground threads. Daemon threads are background threads.
User threads are high priority threads. Daemon threads are low priority threads.
Its life independent. Its life depends on user threads.

GO to index page
Stream in JAVA
What is stream?
 In Java, “stream” essentially refers to an abstraction that is used to produce and consume
flow of sequential information.
 A Stream is linked to a physical layer by java I/O system to make input and output operation
in java.
 In general, a stream means continuous flow of data.

Java encapsulates Stream under java.io package.

A Stream will be an input stream or, an output stream.


InputStream − This is used to read data from a source.
OutputStream − This is used to write data to a destination.

Based on the data they handle there are two types of streams
Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text
data only.
Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of
8 bits. Using these you can store characters, videos, audios, images etc.

File and RandomAccessFile


File Class in JAVA
The File class is an abstract representation of file and directory pathname. A pathname can be
either absolute or relative.
The File class have several methods for working with directories and files such as creating new
directories or files, deleting and renaming directories or files, listing the contents of a directory
etc.
How to create a File Object?
A File object is created by passing in a string that represents the name of a file, a String, or another
File object. For example,

File a = new File("/usr/local/bin/geeks");

Constructors of File Class


File(File parent, String child): Creates a new File instance from a parent abstract pathname and a
child pathname string.
File(String pathname): Creates a new File instance by converting the given pathname string into
an abstract pathname.
File(String parent, String child): Creates a new File instance from a parent pathname string and a
child pathname string.
File(URI uri): Creates a new File instance by converting the given file: URI into an abstract
pathname.
GO to index page
RandomAccessFile Class in JAVA

This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the cursor
we do the read write operations. If end-of-file is reached before the desired number of byte has
been read than EOFException is thrown. It is a type of IOException.

Constructors of RandomAccessFile Class


RandomAccessFile(File file, String mode) : Creates a random access file stream to read from, and
optionally to write to, the file specified by the File argument.
RandomAccessFile(String name, String mode) : Creates a random access file stream to read from,
and optionally to write to, a file with the specified name.

Character Streams
Character stream is also defined by using two abstract classes
at the top of the hierarchy, they are Reader and Writer. These
two abstract classes have several concrete classes that handle
Unicode characters.
Reader classes: Abstract class that define character stream
input.
Writer classes: Abstract class that define character stream
output.
Some important Character stream classes:

Stream class Description


BufferedReader Handles buffered input stream.
BufferedWriter Handles buffered output stream.
FileReader Input stream that reads from file.
FileWriter Output stream that writes to file.
InputStreamReader Input stream that translate byte to character
OutputStreamReader Output stream that translate character to byte.
PrintWriter Output Stream that contain print() and println() method.
Reader Abstract class that define character stream input
Writer Abstract class that define character stream output
GO to index page
Byte Streams
Byte Stream Classes are used to read bytes from an input
stream and write bytes to an output stream.

InputStream Classes - These classes are subclasses of an


abstract class, InputStream and they are used to read bytes
from a source(file, memory or console).

OutputStream Classes - These classes are subclasses of an


abstract class, OutputStream and they are used to write
bytes to a destination(file, memory or console).

Some important Byte stream classes.

Stream class Description


BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard data type.
DataOutputStream An output stream that contain method for writing java standard
data type.
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method

StreamTokenizer Class in Java


The Java.io.StreamTokenizer class takes an input stream and parses it into "tokens", allowing the
tokens to be read one at a time. The stream tokenizer can recognize identifiers, numbers, quoted
strings, and various comment styles.
GO to index page
Field
Following are the fields for Java.io.StreamTokenizer class −
double nval − If the current token is a number, this field contains the value of that number.
String sval − If the current token is a word token, this field contains a string giving the characters
of the word token.
static int TT_EOF − A constant indicating that the end of the stream has been read.
static int TT_EOL − A constant indicating that the end of the line has been read.
static int TT_NUMBER − A constant indicating that a number token has been read.
static int TT_WORD − A constant indicating that a word token has been read.
int ttype − After a call to the nextToken method, this field contains the type of the token just read.

PipedOutputStream Class
The PipedInputStream and PipedOutputStream classes can be used to read and write data
simultaneously. Both streams are connected with each other using the connect() method of the
PipedOutputStream class.

Following are the important points about PipedOutputStream −


 The piped output stream is the sending end of the pipe.
 Attempting to use both objects from a single thread is not recommended as it may deadlock
the thread.
 Data is written to a PipedOutputStream object by one thread and data is read from the
connected PipedInputStream by some other thread.
 The pipe is said to be broken if a thread that was reading data bytes from the connected
piped input stream is no longer alive.

Constructor:
PipedOutputStream() : creates a PipedOutputStream, that it is not connected.
PipedOutputStream(PipedOutputStream inStream) : creates a PipedOutputStream, that it is
connected to PipedInputStream – ‘inStream’.
Methods:
write() : java.io.PipedOutputStream.write(int byte) writes a specified byte to the Piped Output
Stream.

Following are the important points about FileInputStream −


This class is meant for reading streams of raw bytes such as image data.
For reading streams of characters, use FileReader.
Pipes in IO provides a link between two threads running in JVM at the same time. So, Pipes are
used both as source or destination.
PipedInputStream is also piped with PipedOutputStream. So, data can be written using
PipedOutputStream and can be written using PipedInputStream.But, using both threads at the
same time will create a deadlock for the threads.
A pipe is said to be broken if a thread that was providing data bytes to the connected piped output
stream is no longer alive.

GO to index page
Constructor:
PipedInputStream() : creates a PipedInputStream, that it is not connected.
PipedInputStream(int pSize) : creates a PipedInputStream, that it is not connected with specified
pipe size.
PipedInputStream(PipedOutputStream outStream) : creates a PipedInputStream, that it is
connected to PipedOutputStream – ‘outStream’.
PipedInputStream(PipedOutputStream outStream, int pSize) : creates a Piped Input Stream that is
connected to Piped Output Stream with the specified pipe size.

Methods:
int read(): Reads the next byte of data from this piped input stream.The value byte is returned as
an int in the range 0 to 255. This method blocks until input data is available, the end of the stream
is detected, or an exception is thrown.
Bridge classes in JAVA

InputStreamReader & OutputStreamWriter


The InputStreamReader class and The OutputStreamWriter class of the java.io package can be
used to convert data in bytes into data in characters.
The InputStreamReader class works with other input streams. It is also known as a bridge between
byte streams and character streams. This is because the InputStreamReader reads bytes fromp the
input stream as characters.
The OutputStreamWriter class works with other output streams. It is also known as a bridge
between byte streams and character streams. This is because the OutputStreamWriter converts
its characters into bytes.

Methods of InputStreamReader
 read() - reads a single character from the reader
 read(char[] array) - reads the characters from the reader and stores in the specified array
 read(char[] array, int start, int length) - reads the number of characters equal to length from the
reader and stores in the specified array starting from the start
 getEncoding() method can be used to get the type of encoding that is used to store data in the
input stream.
 close() : To close the input stream reader, we can use the close() method. Once
the close() method is called, we cannot use the reader to read the data.

Methods of OutputStreamWriter
 write() - writes a single character to the writer
 write(char[] array) - writes the characters from the specified array to the writer
 write(String data) - writes the specified string to the writer
 getEncoding() method can be used to get the type of encoding that is used to write data to the
output stream.
 close() : To close the output stream writer, we can use the close() method. Once
the close() method is called, we cannot use the writer to write the data.

GO to index page
ObjectInputStream & ObjectOutputStream
We use object streams to read and write Java objects in binary
format. ObjectInputStream and ObjectOutputStream are the main object stream classes provided
by the Java File I/O API.
Basically, the ObjectOutputStream and ObjectOutputStream encodes Java objects using the class
name and object values. And, hence generates corresponding streams. This process is known as
serialization.

Methods of ObjectInputStream
The ObjectInputStream class provides implementations of different methods present in
the InputStream class.
 read() Method
 read() - reads a byte of data from the input stream
 readBoolean() - reads data in boolean form
 readChar() - reads data in character form
 readInt() - reads data in integer form
 readObject() - reads the object from the input stream
 available() - returns the available number of bytes in the input stream
 mark() - marks the position in input stream up to which data has been read
 reset() - returns the control to the point in the input stream where the mark was set.
 skipBytes() - skips and discards the specified bytes from the input stream
 close() - closes the object input stream

Methods of ObjectOutputStream
The ObjectOutputStream class provides implementations for different methods present in
the OutputStream class.
 write() Method
 write() - writes a byte of data to the output stream
 writeBoolean() - writes data in boolean form
 writeChar() - writes data in character form
 writeInt() - writes data in integer form
 writeObject() - writes object to the output stream
 flush() - clears all the data from the output stream
 drain() - puts all the buffered data in the output stream
 close() - closes the output stream

GO to index page

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy