Showing posts with label java exception handling. Show all posts
Showing posts with label java exception handling. Show all posts

Friday, March 1, 2024

EXCEPTION HANDLING IN JAVA

 Java Exception Handling


  • EXCEPTION HIERARCHY
  • USER-DEFINED EXCEPTIONS
  • HOW DOES JVM HANDLE EXCEPTION

Exception handling is a highly efficient method of addressing runtime errors in Java programs as it guarantees regular program operation.

We will study the types of Java exceptions and how they differ from one another in this lesson. and unreviewed exclusions.

A non-trivial or unexpected event that occurs during program execution and interferes with, in Java, the usual execution of a program's instructions is called an exception. The software understands how to handle an exception. Every time a procedure throws an exception, an object is produced. An exception object is what is referred to as such. This file contains the name, description, and program status as of the exception occurrence.

The main reasons for the exception occurring are Incorrect user input Device error Network connection failure limitations (external disk storage) Code error and inability to open an accessible file.

In Java, non-trivial or unexpected events that occur during program execution that obstruct regular program execution are referred to as exceptions. The software understands how to handle an exception. Every time a procedure throws an exception, an object is produced. An exception object is what is referred to as such. This file includes details about the exception, including its name, description, and the state of the application at the time it occurred.

The main reasons for the exception occurring are user input Device error Network connection failure limitations (external disk storage)Code error unable to open an accessible file.

Error: An error provides information or indicates or shows a serious problem that no sane software should attempt to detect.

Exception: An exception gives details or points out circumstances that a reasonable program could try to detect.

Exception hierarchy

Every other exception and error type is descended from the Throwable class. One section is overseen by a reception. This class is used by user programs when they need to catch exceptions. The Null-Pointer-Exception is one of these exceptions. The Java Runtime Environment (JRE) itself uses the second branch, Error, to detect runtime-related errors made by the Java Runtime System (JVM). One such error example is the Stack-Overflow-Error.

Types of exception

Exceptions can be classified in two ways: Built-in Exceptions-Challenged Exception-Unhandled Exception-User Defined Exceptions

Let us discuss the above exception which is as follows: 1. Built-in Exceptions - these are exceptions available in Java libraries. These exceptions are useful for explaining certain error situations.

Checked exceptions: Checked exceptions are called compile-time exceptions because the compiler checks for them during compilation.

Unchecked exceptions: these are not checked, in contrast to checked exceptions. The compiler does not search for these exceptions during compilation. To put it another way, a compilation fault won't be triggered whether we handle or report an unchecked exception that a program raises.

User-Defined Exceptions:

Regretfully, there are times when Java's built-in exceptions just aren't sufficient. Thus, "user-defined exceptions" might also be made by users.

The advantage of using exception handling in Java is Program completion.

We can easily identify the errors in the code and handle them using code-Propagation of errors-Important error message-Identification of error typescript methods Exception information.

1.      printStackTrace()

 The Name of the Exception, Stack Trace, and Description of the Exception are all included in the method's formatted output.

Let us try this with a program:

//program to print the exception information using the printStackTrace() method 

 


Output

java. lang.ArithmeticException: / by zero

at sdf.main(File.java:10)
2.      toString()
Exception information is printed via the ToString() function. Name: Exception Description.

Ex. // program that uses the toString() function to output the error information


Output

java. lang.ArithmeticException: / by zero

     getMessage()

 The getMessage() method only prints the exception description.

Ex. // program that uses the getMessage() function to output the exception information 

 

Output

by zero

How does JVM handle Exception?

A method's default response to an exception is to generate an exception object and send it to the Java Virtual Machine (JVM). The name, description, and current state of the application, along with any other relevant data, are all contained in the exception object. When the runtime system creates and handles an exception object, an exception is "thrown". It's possible that several methods were called to enable the problematic method. This collection of techniques is called the Call Stack. This is when something else occurs.

The runtime system looks for a method in the call stack that contains the exception handling code. This portion of code is also known as the exception handler.

The runtime system searches for the code that threw the exception by starting at the top of the call stack and moving down.

When it finds a suitable handler, it steps through the exception whom it The thrown object type of an exception must match the exception's type for a handler to be considered suitable.

The exception is issued again if after the runtime system has examined every method on the call stack, no suitable handler is discovered. To the default exception handler of the runtime system. Should an unusual program termination occur, this handler will output pertinent exception data in the manner shown below.

Exception in thread "xxx" Name of Exception: Description
... ...... ..  // Call Stack

Here we will examine an example that shows how the runtime system searches the call stack for the correct 
code to handle exceptions.



                  } 
}
Output 
by zero

MULTITHREADING IN JAVA

 Java Multithreading


  • ADVANTAGES
  • PROCESS BASED MULTITASKING
  • THREAD BASED MULTITASKING
  • USE OF THREAD
  • JAVA THREAD CLASS 
  • JAVA THREAD METHOD
  • THREAD VC RUNNABLE CLASS 
  • LIFE CYCLE OF THREAD
  • JAVA THREAD PRIORITY IN MULTITHREADING

Java's multithreading functionality allows for the simultaneous execution of several threads. The smallest processing unit is a thread, which is a light subprocess. Multiprocessing and multithreading are used to do several tasks at once.

Because threads can benefit from shared memory, multithreading is favored over multiprocessing. By not creating a specific region, they preserve memory, and thread context swapping is faster than process execution. Java multithreading is widely used in games, animations, and other related tasks.

Advantages of multithreading: -

  1. The user won't be hampered since threads are autonomous and allow many apps to execute at once.
  2. It saves time to perform many tasks at once.
  3. Other threads are independent, therefore this won't affect them in any way. procedures when a single thread encounters an issue.

Multitasking is of two types: -

  • Process-based multitasking (Multiprocessing)
  • Thread based multitasking (Multithreading)

Process-based multitasking

  • Each process has an address in memory. In other words, each process allocates a separate area of ​​memory.
  • The process is heavy.
  • The cost of transferring data between processes is high.
  • Switching from one process to another requires some time to save and load registers, memory cards. . , and lists. , and so on.

Thread-based multitasking (Multithreading)

  •       Threads share the same address space.
  •       Threading is lightweight.
  •       Communication between threads is low.

What is the use of thread in Java?

A thread is a light subprocess that is the smallest processing unit. We have a separate execution path here.

Threads operate on their own. One thread may experience an exception without impacting the others. It utilizes a section of shared memory.

At runtime, several threads can switch contexts. inside an operating system, there can be several processes and multiple threads inside a single process.

Java thread class

Java has a class called Thread this Thread class is used for thread programming. You may create and execute thread activities using the constructors and methods that the Thread class offers. The Thread class makes use of the Runnable interface to enhance other classes' capabilities.

Java thread methods


 


Thread creation by implementing the runnable interface

The java. lang package will be implemented by a newly formed class. creates a runnable interface and substitutes our own run() method for the run() function. The Thread object is then created, and its start() function is called.

Let us understand by a program

// the Runnable Interface

Thread class Vs Runnable class

Java does not enable multiple inheritance; therefore our expanded Thread class is unable to extend any other classes. Once we implement the Runnable interface, our class still can extend to other base classes.

Basic thread functionality can be achieved by extending the Thread class, as it provides some built-in methods such as produce(), interrupt(), etc., these methods are not available in the Runnable interface.

When you use the runnable command, an object that may be shared by several threads is produced.

The life cycle of a Thread (Thread states)

A thread lies only in one of the shown states at any instant:

1.      New State

2.      Runnable State

3.      Blocked State

4.      Waiting State

5.      Timed Waiting State

6.      Terminated State

Let us understand each one of them separately:

New thread: A new thread when it is created goes into a new state. When a thread gets to this point, it hasn't started yet. If and only if a thread's code hasn't begun, it is said to be in a fresh state.

Running state: A thread enters the running state when it's ready to go. The thread may currently be operating, or it may be ready to start running at any time. The thread scheduler's role is to determine when the thread will execute.

In a multithreaded program, time is assigned to each thread separately. Each thread runs for a certain length of time before halting and handing the CPU to another thread so that additional threads can operate. Every thread that is ready for the CPU to run waits patiently for the CPU to execute an active thread when this happens.

Blocked: Right now, one thread is unable to obtain the lock, while another thread is managing to accomplish so. A thread changes from being blocked to being in the running state when it is locked.

Waiting state: A thread has to invoke the wait() or join() method to go into the waiting state. It goes into the running state when it gets a notification from another thread or when that thread ends.

Timed Wait: Calling a method with a timeout parameter causes a thread to be scheduled to wait. We refer to this as a timed wait. The thread will remain in this state until it times out or gets a notification. If a thread calls for anything like sleep or a conditional wait, it's put into a timed wait.

Terminated state: A thread may quit its current state if any of the following circumstances are met: It conventionally departs the body. This takes place once the thread's code has finished running.

Because of the appearance of an unforeseen issue, such as a segment fault or an exception that was ignored.

Implementing thread states in Java

To find out the current status of a thread while dealing with Java, use the Thread.getState() method. It includes the java.lang library. The state variables are defined as an enumeration by the Thread class. It is summarized below.

1)      1) NEW

It means the thread has not started yet

Ex: public static final Thread.State NEW
 
2)      Runnable 
 
The thread state of the running thread. In executable mode, a thread starts in the Java 
virtual machine, but can wait for other operating system resources, such as the CPU.
Ex. public static final Thread.State RUNNABLE
 
3)      Blocked 
A thread goes into a blocked state while it waits for the screen lock to be imposed. 
A thread cannot leave a blocked state unless it invokes an Object to return to a 
synchronized block or function, or it must wait for the screen lock to move to a 
synchronized block or Object. wait().
Ex. public static final Thread. State BLOCKED
 
4)      Waiting 
Thread state for a waiting thread. A thread is waiting because it calls one of the 
following methods: Object. wait with no timeout thread. Join with no 
timeout LockSupport.park.
 
Ex. public static final Thread.State WAITING
 
5)      Timed waiting 
The condition of a thread that is waiting for a given amount of time. When a thread 
calls one of the following methods with a positive timeout provided, the thread times 
out while it waits: Thread.sleepObject.wait with timeout thread. join with 
timeoutLockSupport.parkNanosLockSupport.parkUntil.
 
Ex. public static final Thread.State TIMED_WAITING
 
6)      Terminated 
 
Thread state of the finished thread. The thread is ready.
 
Ex. public static final Thread.State TERMINATED

 

Below is the implementation of the thread:

// Java program to demonstrate thread states


 





Java thread priority in multithreading
Thread scheduling is the process of allocating a processor to a thread according to its 
priority; As we already studied Java is an OOP language that runs in a multi-threaded 
environment. In Java, priority is assured at the time of thread creation. Programmers 
have the option to manually designate a priority during thread formation, or the JVM 
can do it for them automatically.
Each thread in this context has a priority, which is expressed as a number between 1 and 10,
or, to put it more simply, each object has a priority.
The exception is default priority is 5. Minimum priority is 1. Maximum priority is 10. 
Here 3 constants are defined in it as follows:\public static int NORM_PRIORITY\public 
static int MIN_PRIORITY\ public static int MAX_PRIORITY
To find out how the task is done inside, let's talk about it using an example. Here, we make 
the following use of the data gathered above: 

We use the current Thread() method to know the name of the current thread. The developer can also use the setName() method if they want to name the threads according to the option for understanding.getName() method is used to get the thread name.

The accepted priority value of a thread is between 1-10.

Let's discuss how we can get and prioritize a thread in Java. public final int getPriority(): The method java. lang.Thread.getPriority() gives the priority of the given thread.public final void set Priority(int newPriority): The method java.lang.Thread.setPriority() sets the preference of the thread to a new thread priority. This method throws an IllegalArgumentException if the value of the new Priority parameter exceeds the min(1) and max(10) limits.

Let us have a program to understand this:

Let us have a program to understand this:




Output Explanation:

The highest priority thread can execute first when thread execution is prioritized. Assume that the priorities of threads 1, 2, and 3 are 4, 6, and 1, respectively. As a result, thread t2 is started with a maximum priority of 6, and then thread t1 and thread t3 come next. The priority of the main thread always remains 5, however, it can be modified at a later time. Every other thread's default priority is set by the priority of the main thread.

What happens if we assign the same priority to every thread, you might wonder. All thread handling is done using the thread scheduler. The example below of what happens when the priorities are the same can be referred to and discussed later as an explanation of the result to better understand conceptually and practically.

Featured Post

ASSOCIATION RULE IN MACHINE LEARNING/PYTHON/ARTIFICIAL INTELLIGENCE

Association rule   Rule Evaluation Metrics Applications of Association Rule Learning Advantages of Association Rule Mining Disadvantages of ...

Popular