0% found this document useful (0 votes)
13 views41 pages

Unit-3 (JP)

Uploaded by

premsagark3101
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)
13 views41 pages

Unit-3 (JP)

Uploaded by

premsagark3101
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/ 41

Exceptions in Java

UNIT-III
Exceptions in Java
• In Java, an Exception is an unwanted or unexpected event, that
occurs during the execution of a program, i.e. at run time, that
disrupts the normal flow of the program’s instructions.
• Exceptions can be caught and handled by the program.
• When an exception occurs within a method, it creates an object.
• This object is called the exception object.
• It contains information about the exception, such as the name and
description of the exception and the state of the program when the
exception occurred.
Advantages of handling
Exceptions
• Separating Error-Handling Code from "Regular" Code
• Grouping and Differentiating Error Types
• Will not stop the entire program when an exception is raised.
Major reasons why an exception
Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Error : serious problems
• Errors represent irrecoverable conditions such as Java virtual
machine (JVM) running out of memory, memory leaks, stack
overflow errors, library incompatibility, infinite recursion, etc.
• Errors are usually beyond the control of the programmer, and we
should not try to handle errors.
Difference between Error and Exception

• Error: An Error indicates a serious problem that a


reasonable application should not try to catch.
• Exception: Exception indicates conditions that a
reasonable application might try to catch.

• All exception and error types are subclasses of the


class Throwable.
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
exception, and even if we didn’t handle or declare it, the program
would not give a compilation error.
Unchecked Exceptions
• ArithmeticException This occurs when an illegal arithmetic operation is performed, such as division
by zero.
• ArrayIndexOutOfBoundsException This occurs when an invalid index is accessed in an array.
• NullPointerException This occurs when an attempt is made to use an object reference that has not
been initialized.
• NumberFormatException This occurs when an attempt is made to convert a string into a numeric
type, but the string is not a valid number.
• IllegalArgumentException This occurs when a method is passed an illegal or inappropriate
argument.
• ClassCastException This occurs when an object is cast to a class of which it is not an instance.
• IllegalStateException This occurs when a method is invoked at an illegal or inappropriate time.
• UnsupportedOperationException This occurs when an operation is not supported.
• NegativeArraySizeException this occurs when an attempt is made to create an array with a
negative size.
• ConcurrentModificationException This occurs when a collection is modified while it is being
iterated in a way that’s not allowed.
Checked Exceptions
• IOException - Issues with input/output operations.
• FileNotFoundException - File not found.
• ClassNotFoundException - Class not found during runtime.
• SQLException - Errors in database access.
• InterruptedException - A thread is interrupted while sleeping or waiting.
• NoSuchMethodException - No method with the specified name.
• InvocationTargetException - Exception thrown by an invoked method through
reflection.
• CloneNotSupportedException - Attempt to clone an object that doesn’t support
cloning.
• IllegalAccessException - Reflective access to a class or method that is not
accessible.
• InstantiationException - Attempt to instantiate an abstract class or interface.
Exception Handling Keywords
(Clauses) in Java
Syntax
try
{
//code to be monitored for an exception
throw exception_object //optional –can use to throw exception explicitly
//throw an exception object to the Java Runtime
}
catch(exception_object)
{
//exception handler for catching the exception_object
}
finally
{
//The code will get executed in any case
}
Multiple catch clauses
• In some situations more than one exception can raise by single piece
of code
• To handle this we can write multiple catch clauses
Nested try statement
• Try statements can be nested (try statement inside another try)
• If inner try doesnot have a catch handler for particular exception, the
stack is unwound and next try statement’s catch handler are
inspected for a match.
Throw clause
• The throw clause can be used to throw the exception explicitly.
Syntax
throw ThrowableInstance;
Example:
throw new ArithmeticException(<“message of exception”>);

• ThrowableInstance object of type Throwable or a subclass of Throwable.


• If the thrown exception is not caught immediate-catch it can be thrown to next level try-
catch (could be in the nested or in the calling method)
• We can even rethrow the same exception next-level try-catch.
• Once the throw statement is executed the remaining statements after throw will be
unreachable.
Throws clause
• If a method is capable of causing an exception that it does not
handle, it must specify this behavior so that the caller method can
guard itself against exception.
• We can do this by including a throws clause in the method
declaration.
• A throws clause lists the types of exceptions that a method throws.
Syntax
modifiers return_type method_name(Parameters_list) throws exception_list
{
----
}
example:
public void readValues() throws IOException,NumberFormatException
{
---
}
Some important Throwable
class methods - can be access
through any Exception object
• String getMessage(): Returns the detail message of the throwable.
• String toString(): Returns a short description of the throwable,
including the class name and message.
• void printStackTrace(): Prints the throwable and its stack trace to the
standard error stream.
• Throwable getCause(): Returns the cause of the throwable or null if
none exists.
Other methods
• String getLocalizedMessage(): Returns a localized description of the
throwable.
• Throwable initCause(Throwable cause): Initializes the cause of this
throwable.
• printStackTrace(PrintStream s): Prints the throwable and its stack
trace to the provided PrintStream.
• printStackTrace(PrintWriter s): Prints the throwable and its stack
trace to the provided PrintWriter.
• fillInStackTrace(): Records the current stack trace for this throwable.
Creating User-defined
Exceptions
• Create your own exception as to handle situations specific to your
applications.
• To do this, create a subclass of Exception class(which is ofcourse a
subclass of Throwable)
• The Exception class does not define any methods of its own, but
inherits the methods of Throwable.
• You may override one or more methods of these in the exception
classes you create.
• In general, we override toString() method to add the description for
our Exception object.
Task:
• Explore Chained Exceptions
• Using single catch for catching multiple Exceptions using | (pipe
symbol)

• Also explore Java Annotations


Multithreading in Java
What is a thread?

• A thread is a lightweight sub-process, the smallest unit of processing.


• Multiprocessing and multithreading, are both used to achieve
multitasking.
• Multiprocessing- executing multiple processes concurrently
• Multithreading- executing multiple threads concurrently
• Every program we write has at least one thread i.e main(). JVM is
responsible for creating the main thread.
• Threads are executed by processor according to the scheduling by the
Java Runtime System by assigning Priority to every thread.
Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you
can perform multiple operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an


exception occurs in a single thread.
Thread life cycle
Thread states
• New  just created
• Runnable ready for execution
• Running running or executing
• Waiting/ blocked/sleeping suspended or waiting
• Dead  terminated successfully or killed
Thread creation
• Using Thread class the class must extend from Thread class

• Using Runnable Interface the class must implement Runnable


interface
Thread class
Thread class is available in java.lang package
Its declaration Is
public class Thread extends Object implements Runnable

The thread class has various predefined methods. One method which starts the
execution of the thread is run().

The thread functionality can only be achieved by overriding run() method.


Public void run()
{
----
}
Thread class constructors
• Thread()
• Thread(String threadname)
• Thread(ThreadGroup threadgroup, String threadname)
The methods of Thread class
• public static Thread currentThread() - Static method that returns a
reference to the currently executing thread.
• public void start() - Starts the thread, calling its run() method
asynchronously.
• public void run() - Defines the code that constitutes the thread's task,
typically overridden in a subclass.
• public static void sleep(long millis) throws InterruptedException
-Pauses the thread for the specified number of milliseconds.
• public static void sleep(long millis, int nanos) throws
InterruptedException
-Pauses the thread for the specified milliseconds and nanoseconds.
• public void interrupt() - Interrupts the thread if it is sleeping, waiting, or
otherwise blocked.

• public boolean isInterrupted() - Checks if the thread has been interrupted


without clearing the interrupt status.

• public final void join() throws InterruptedException –

Waits for this thread to die before proceeding.


• public final void join(long millis) throws InterruptedException
Waits at most the given milliseconds for this thread to die.
• public final void join(long millis, int nanos) throws InterruptedException -
Waits at most the specified milliseconds and nanoseconds for this thread
to die.
• public void setPriority(int newPriority) - Sets the priority of the thread.
• public int getPriority() - Returns the priority of the thread.
• public void setName(String name) - Changes the name of the thread.
• public String getName() - Returns the name of the thread

• public final void setDaemon(boolean on)

Marks the thread as a daemon thread (background service


thread).

• public final boolean isDaemon()

Checks if the thread is a daemon thread.


• public long getId() - Returns the unique identifier of the thread.

• public State getState() - Returns the current state of the thread (e.g., NEW,
RUNNABLE, BLOCKED, etc.).

• public static void yield() - Suggests that the current thread yields its execution time
for other threads.
• public final void wait(long timeout) throws InterruptedException –
Causes the current thread to wait for the specified time until it is notified
or interrupted (inherited from Object class).
• public final void wait(long timeout, int nanos) throws InterruptedException
Causes the current thread to wait for the specified time (in milliseconds and
nanoseconds) until it is notified or interrupted (inherited from Object class).
• public final void wait() throws InterruptedException
Causes the current thread to wait until it is notified or interrupted (inherited
from Object class).
• public final void notify() - Wakes up a single thread that is waiting on
this object’s monitor (inherited from Object class).
• public final void notifyAll() - Wakes up all threads that are waiting on
this object’s monitor (inherited from Object class).
Main Thread
• The main thread is created by JVM itself.
• Apart from the main thread JVM creates some invisible threads to
take care of operations like garbage collection, object finalization etc.
• The main thread spawns other threads (generates) which are called
child threads.
• When threading is implemented the main thread is the last to finish
the execution.
Runnable interface
• The Runnable interface has a single abstract method, run(), which
contains the code that defines the task to be executed.
• To execute code in a separate thread using Runnable interface needs
to be passed to a Thread object.
• Java encourages the use of Runnable interface nstead of directly
extending the Thread class. This is because Java does not support
multiple inheritance (a class can only extend one class). By
implementing Runnable interface the class can still extend other
classes.
How to Use Runnable:
• Implement the Runnable interface: Create a class that implements
Runnable and provides the logic for the run() method.
• Create a Thread object: Pass an instance of the Runnable
implementation to the Thread constructor.
• Start the thread: Call the start() method of the Thread object to
execute the task concurrently in a new thread.
Thread Synchronization
• Thread synchronization is a way to control the access of multiple
threads to shared resources like variables, files, or objects to prevent
unexpected results.
• When two or more threads try to access and modify a shared
resource (e.g., a variable or a method) at the same time, it can lead to
inconsistent or incorrect results. This is called a race condition.
• Java uses a synchronized keyword to restrict access to certain
methods or blocks of code, allowing only one thread at a time to
execute the synchronized code. This way, shared resources are
protected.
synchronized method:
• A method can be declared as synchronized

Access_modifier synchronized return_type method_name(parameters)


{
---
}
synchronized block
The object of any class can be made synchronized with the help of a
synchronized block.

synchronized(object)
{
///
}

You might also like