Java Notes Unit IV

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Errors and Exception:-

Java Errors:- The error indicates a problem that mainly occurs due to the lack of
system resources and our application should not catch these types of problems. Some
of the examples of errors are system crash error and out of memory error. Errors
mostly occur at runtime that's they belong to an unchecked type.
Types of Errors:
Errors may broadly classified into two categories:
i) Compile-time errors
ii) Run -time errors
i) Compile-time errors:
All syntax errors will be detected and displayed by the java compiler and therefore
these errors are known as compile-time errors. This compiler error indicates
something that must be fixed before the code can be compiled.
Most frequent Compile-Time errors are:
• Missing Parenthesis ( } )
• Printing the value of variable without declaring it
• Missing semicolon (terminator)
• Misspelling of identifiers and keywords
• Missing of double quotes in strings
ii) Run -time errors:
Sometimes, a program may compile successfully creating the .class file but not run
properly. Such programs may produce wrong results due to wrong logic and may
terminate due to errors such as stack overflow.
Most frequent Run -time errors are:
• Dividing an integer by zero
• Accessing an element that is out of the bounds of an array
• Passing a parameter that is not in a valid range or value for a method
• Converting invalid string to a number.
Exception:- An exception is an event that occurs during the execution of a program
that disrupts the normal flow of instructions during the execution of a program.
Exceptions are objects that represent errors that may occur in a Java program. An
exception is a condition that is caused by a run-time error in the program.
Exception Handling:-

syntax:
..........
..........
try
{
statement; // generates an exception
}
catch (Exception-type e)
{
statement; // processes the exception
}
..........
..........
Example:

class ExeceptionExample {
public static void main(String args[]) {
int a = 10;
int b = 5;
int c = 5;
int x, y;
try {
x = a / (b - c); // generates an exception
} catch (ArithmeticException e) {
System.out.println("Division by zero"); // processes the exception
}
y = a / (b + c);
System.out.println("y = " + y);
}
}

Finally and Throw keywords:-


The finally keyword:-
Java supports another statement known as the finally statement that contains all the
crucial statements that must be executed whether an exception occurs or not. The
statements present in this block will always execute regardless of whether an
exception occurs in a try block or not such as closing a connection, stream, etc.
It may be added immediately after the try block or after the last catch block shown
as follows:
Syntax 1:
try
{
statement; // generates an exception
}
finally
{
statement; // final statement
}

Syntax 2:
try
{
statement; // generates an exception
}
catch( Exception-type e)
{
statement; // processes the exception
}
catch( Exception-type e)
{
statement; // processes the exception
}
finally
{
statement; // final statement
}

Example:
class FinallyExample {
public static void main(String args[]) {
try {
int num = 25 / 5;
System.out.println(num);
} catch (ArithmeticException e) {
System.out.println(e);
} finally { // finally used after catch block
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}

The throw keyword:


The Java throw keyword is used to explicitly throw a single exception. When we
throw an exception, the flow of the program moves from the try block to the catch
block. The throw keyword is used to create a custom error. The throw statement is
used together with an exception type.
Example:
class ThrowExample {
public static void divideByZero() {

// throw an exception
throw new ArithmeticException("Trying to divide by 0");
}

public static void main(String[] args) {


divideByZero();
}
}

Multithreading:-
Multithreading in Java is a process of executing multiple threads simultaneously.
ava uses threads by using a "Thread Class". A single thread is basically a
lightweight and the smallest unit of processing. Thread class provides constructors
and methods to create and perform operations on a thread.
Creating Threads
Creating threads in java is simple. There are two ways to create a thread:
i) By extending Thread class
ii) By implementing Runnable interface.

i) By extending Thread class:


Create a thread by a new class that extends the Thread class and create an instance
of that class. The extending class must override the run() method which is the entry
point of the new thread.
Example:
class Multithread extends Thread { //extending from Thread class
public void run() {
System.out.println("thread is running...");
}
public static void main(String args[]) {
Multithread t = new Multithread(); // object t is created for Multithread class
t.start(); //Thread method
}

ii) By implementing Runnable interface:


The easiest way to create a thread is to create a class that implements the runnable
interface. After implementing runnable interface , the class needs to implement
the run() method, which is public void run().
• The run() method introduces a concurrent thread into your program. This
thread will end when run() returns.
• You must specify the code for your thread inside run() method.
• The run() method can call other methods, can use other classes, and declare
variables just like any other normal method.
Example:
class Multithread implements Runnable { //implementing runnale interface
public void run() {
System.out.println("thread is running...");
}

public static void main(String args[]) {


Multithread m = new Multithread();
Thread t = new Thread(m); // object t is created for Thread class
t.start(); //Thread method
}
}
Stopping a Thread:
Whenever we want to stop a thread from running further, we may do so by calling
its stop() method. This causes a thread to stop immediately and move it to its dead
state. It forces the thread to stop abruptly before its completion.
syntax:
t.stop();

Blocking a Thread:
A thread can also be temporarily suspended or blocked from entering into the
runnable and subsequently running state by using either of the following thread
methods:
sleep(t); // blocked for ‘t’ milliseconds

suspend(); // blocked until resume() method is invoked

wait(); // blocked until notify () is invoked


These methods cause the thread to go into the blocked (or not-runnable) state. The
thread will return to the runnable state when the specified time is elapsed in the
case of sleep( ), the resume() method is invoked in the case of suspend( ), and the
notify( ) method is called in the case of wait().
The life cycle of a Java Thread:-
The life cycle of the thread in java is controlled by JVM. The java thread states are
as follows:
• Newborn
• Runnable
• Running
• Non-Runnable (Blocked)
• Dead (Terminated)

1. Newborn :
When we create a new Thread object using new operator, thread state is New
Thread. At this point, thread is not alive and it’s a state internal to Java
programming.
2. Runnable:
When we call the start() function on the Thread object, its state is changed to
Runnable. The control is given to the Thread scheduler to finish its execution.
Whether to run this thread instantly or keep it in a runnable thread pool before
running, depends on the OS implementation of the thread scheduler.
3. Running:
When a thread is executing, its state is changed to Running. Thread scheduler picks
one of the threads from the runnable thread pool and changes its state to Running.
Then CPU starts executing this thread. A thread can change state to Runnable,
Dead, or Blocked from running state depends on time slicing, thread completion of
the run() method, or waiting for some resources.
4. Blocked:
A thread can be waiting for other threads to finish using thread join or it can be
waiting for some resources to available. Once the thread wait state is over, its state
is changed to Runnable and it’s moved back to the runnable thread pool.
5. Dead:
Once the thread finished executing, its state is changed to Dead and it’s considered
to be not alive. A thread is in the terminated or dead state when its run() method
exits.

You might also like