Java Exception
Java Exception
Java Exception
Exception is an event that arises during the execution of the program, and it
terminates the program abnormally. It then displays system generated error
message.
Exception Handling:
Exception handling is the mechanism to handle the abnormal termination of
the program.
For example :ClassNotFoundException, NumberFormatException,
NullPointerException etc.
Error Exception
It cannot be caught. It can be handled by try and catch block.
Errors are by default unchecked Exception can be either checked or
type. unchecked type.
It is defined in java.lang.Error It is defined in java.lang.Exception
package. package.
Errors are generally caused by Exceptions are generally caused by
environment in which application is application itself.
running.
Types of Exceptions
1. Checked Exceptions
Checked exceptions are also known as compiled time exception, because such
exceptions occur at compile time.
Java compiler checks if the program contains the checked exception handler
or not at the time of compilation.
All these exceptions are subclass of exception class.
Developer has overall control to handle them.
For example: SQLException, IOException, ClassNotFoundException etc.
import java.io.File;
import java.io.PrintWriter;
public class Checked_Demo
{
public static void main(String args[])
{
File file=new File("E://abc.txt");
PrintWriter pw = new PrintWriter("file");
}
}
Output:
error: FileNotFoundException
2. Unchecked Exceptions
Unchecked exceptions are also known as runtime exception.
These include logic errors or improper use of API.
For example: ArrayIndexOutOfBoundException, NullPointerException,
ArithmeticException.
class Uncheked_Demo
{
public static void main(String args[])
{
int a = 10;
int b = 0;
Dambal Sir (Sangola College,Sangola) 2
int c = a/b;
System.out.println(c);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Built-in exceptions
Built-in exceptions are the exceptions which 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.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic
operation.
2. 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.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is
not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing
, and it is interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object.
Null represents nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a
numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either
negative than the size of the string
Examples of Built-in Exception:
Arithmetic exception
// Java program to demonstrate ArithmeticException
ClassArithmeticException_Demo
{ public static void main(String args[])
{ try
{
NullPointer Exception
//Java program to demonstrate NullPointerException
ClassNullPointer_Demo
{ public static void main(String args[])
{ try
{
String a = null; //null value
System.out.println(a.charAt(0));
}
catch(NullPointerException e)
{
System.out.println("NullPointerException..");
}
}
}
output:
NullPointerException..
StringIndexOutOfBound Exception
// Java program to demonstrate StringIndexOutOfBoundsException
ClassStringIndexOutOfBound_Demo
{ public static void main(String args[])
{ try
{
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e)
{
System.out.println("StringIndexOutOfBoundsException");
}
}
}
Output: StringIndexOutOfBoundsException
{ try
{ // Following file does not exist
File file = new File("E://file.txt");
FileReaderfr = new FileReader(file);
}
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
}
}}
Output:
NumberFormat Exception
// Java program to demonstrate NumberFormatException
ClassNumberFormat_Demo
{ public static void main(String args[])
{ try
{ // "akk" is not a number
Int num = Integer.parseInt ("akk") ;
System.out.println(num);
}
catch(NumberFormatException e)
{
System.out.println("Number format exception");
}
}
}
Output:
ArrayIndexOutOfBounds Exception
// Java program to demonstrate ArrayIndexOutOfBoundException
ClassArrayIndexOutOfBound_Demo
{ public static void main(String args[])
{ try
{ int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of size 5
The try block contains the code that might throw an exception. The try block
contains at least one catch block or finally block.
A catch block must be declared after try block. It contains the error handling
code. A catch block executes if an exception generates in corresponding try
block.
Syntax
try
{
//code that cause exception;
}
catch(Exception_type e)
{
//exception handling code
}
class TryCatchDemo
{
public static void main(String args[])
{
int a = 30, b = 3, c = 3;
int result1, result2;
try
{
Dambal Sir (Sangola College,Sangola) 6
result1 = a / (b - c);
}
catch(ArithmeticException ae)
{
System.out.println("Divided by zero: "+ae);
}
result2 = a / (b + c);
System.out.println("Result2 = "+result2);
}
}
Output :
Divided by zero: java.lang.ArithmeticException: / by zero
Result2 = 5
class ExceptionDemo
{
public static void main(String args[])
{
try
{
int arr[] = new int[5];
arr[2] = 5;
System.out.println("Access element two: " + arr[2]);
arr[7] = 10;
System.out.println("Access element seven: "+ arr[7]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown:" + e);
}
System.out.println("End of the block");
}
}
Output :
Access element two: 5
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7
End of the block
10 0
Enter second value except zero.
5
Enter at least two numbers.
10 a
Enter only numeric value.
The code present in finally block will always be executed even if try block
generates some exception.
Finally block must be followed by try or catch block.
It is used to execute some important code.
Finally block executes after try and catch block.
Syntax:
try
{
// code
}
catch(Exception_type1)
{
// catch block1
}
Catch(Exception_type2)
{
//catch block 2
}
finally
{
//finally block
//always execute
}
class FinallyTest
{
public static void main(String args[])
{
int arr[] = new int[5];
try
{
arr[7] = 10;
System.out.println("Seventh element value: " + arr[7]);
}
catch(ArrayIndexOutOfBoundsException ai)
{
System.out.println("Exception thrown : " + ai);
}
finally
{
arr[0] = 5;
System.out.println("First element value: " +arr[0]);
System.out.println("The finally statement is executed");
}
}
}
The throw keyword in Java is used to explicitly throw our own exception.
It can be used for both checked and unchecked exception.
Syntax:
throw new Throwable subclass;
Example : A program to illustrate throw keyword in java
Throw Throws
It is used to throw own It is used when program does not handle
exception. exception via try block.
It handles explicitly thrown It handles all exceptions generated by program.
exceptions.
Cannot throw multiple Declare multiple exception e.g.
exceptions. public void method() throws, IOException,
SQLException.
It is used within the method. It is used within method signature.
Dambal Sir (Sangola College,Sangola) 11
final
final is a keyword.
It is used to apply restriction on class, method and variables.
final class cannot be inherited, final method cannot be overridden and final
variable cannot be changed.
finally
finalize ()
finalize is a method.
This method is associated with garbage collection, just before collecting the
garbage by system.
It is called automatically.
The exceptions that we create on our own are known as custom exception.
These exceptions are created to generate a solution for anticipated errors as
per programmer’s need.
A “Custom exception class” must be extended from “Exception class”.
// CustomException.java
// CustomDemo.java
Output:
i= 2
i= 4
i= 6
i= 8
Exception in thread "main" CustomException: My Exception Occurred
at CustomDemo.display(CustomDemo.java:11)
at CustomDemo.main(CustomDemo.java:4)
Multithreading
New State: Soon after the creation of a thread, it is said to be in the new state.
Dambal Sir (Sangola College,Sangola) 13
Runnable State: The life of a thread starts after invoking the start () method.
The start() method invokes the run () method.
Running State: When the thread is currently running, it is in the state of
running.
Wait State: When other threads are holding the resources, the current thread
is said to be in wait state
Dead State: When the thread has completed the execution of run () method, it
is said to be in dead state.
Creating Thread
// MainThread.java
Output:
Run method: Run
Dambal Sir (Sangola College,Sangola) 14
Run method: Run
Run method: Run
Run method: Run
Run method: Run
Run method: Run
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Thread
Run method: Thread
Output:
Run method: Thread
Run method: Run
Run method: Thread
Methods Description
public void start( This method invokes the run() method, which causes the
) thread to begin its execution.
public void run( ) Contains the actual functionality of a thread and is usually
invoked by start() method.
public static void Blocks currently running thread for at least certain
sleep (long millisecond.
millisec)
public static void Causes the current running thread to halt temporarily and
yield ( ) allow other threads to execute.
public static It returns the reference to the current running thread object.
Thread
currentThread ( )
public final void Changes the priority of the current thread. The minimum
setPriority (int priority number is 1 and the maximum priority number is
priority) 10.
public final void Allows one thread to wait for completion of another thread.
join (long
millisec)
public final Used to know whether a thread is live or not. It returns true
boolean isAlive ( ) if the thread is alive. A thread is said to be alive if it has
been started but has not yet died.
public void Interrupts the thread, causing it to continue execution if it
interrupt ( ) was blocked for some reason.
Thread Priorities:
}
Dambal Sir (Sangola College,Sangola) 17
public static void main(String args[])
{
}
}
}
public static void main(String args[])
{
}
public static void main(String args[])
{
JavaSetPriorityExp3 t1=new JavaSetPriorityExp3(); // creating one thread
t1.setPriority(Thread.NORM_PRIORITY); //print the normal priority of thread
t1.start(); // starting the thread
}
}
Example 4: User define Priority Thread
public class JavaSetPriorityExp4 extends Thread
{
public void run()
{
System.out.println("running...");
}
public static void main(String args[])
{
}
}
Output:
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);
// Main thread
System.out.print(Thread.currentThread().getName());
What is Synchronization?
Synchronization is the process of allowing threads to execute one after another.
It provides the control to access multiple threads to shared resources.
When a method is declared as synchronized, the threads hold the monitor for
that thread object. If any thread uses synchronized method then other threads
are blocked until that thread releases the monitor.
Synchronization Block
Syntax:
synchronized
{
// code
}
Example : Working of synchronization block
class SynchDemo
{
void printNumber(int n)
{
synchronized(this)
{
Dambal Sir (Sangola College,Sangola) 20
for(int i=1;i<=5;i++)
{
System.out.println(n+" * "+i+" = "+n*i);
try
{
Thread.sleep(400);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MainThread1 extends Thread
{
SynchDemo t;
MainThread1(SynchDemo t)
{
this.t=t;
}
public void run()
{
t.printNumber(4);
}
}
class MainThread2 extends Thread
{
SynchDemo t;
MainThread2(SynchDemo t)
{
this.t=t;
}
public void run()
{
t.printNumber(10);
}
}
public class TestSynchronizedBlock
{
public static void main(String args[])
{
SynchDemo obj = new SynchDemo();
MainThread1 t1=new MainThread1(obj);
MainThread2 t2=new MainThread2(obj);
t1.start();
t2.start();
}
}
Synchronization Method
For example:
public final void wait () throws InterruptedException,
public final void wait (long timeout) InterruptedException
Syntax:
public final void notify ()
Syntax:
public final void notifyAll()
class Customer
{
int amount=10000;
Dambal Sir (Sangola College,Sangola) 23
synchronized void withdraw(int amount)
{
System.out.println("going to withdraw...");
if(this.amount<amount)
{
System.out.println("Less balance; waiting for deposit...");
try
{wait();
}
catch(Exception e)
{
}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}
class Test
{
public static void main(String args[])
{
final Customer c=new Customer();
new Thread()
{
public void run(){c.withdraw(15000);
}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}
}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
The start() method of thread class is used to begin the execution of thread. The
result of this method is two threads that are running concurrently: the current
thread (which returns from the call to the start method) and the other thread
(which executes its run method).
The start() method internally calls the run() method of Runnable interface to
execute the code specified in the run() method in a separate thread.
The run() method of thread class is called if the thread was constructed using a
separate Runnable object otherwise this method does nothing and returns.
When the run() method calls, the code specified in the run() method is
executed. You can call the run() method multiple times.
The run() method can be called using the start() method or by calling the run()
method itself. But when you use run() method for calling itself, it creates
problems.
The resume() method of thread class is only used with suspend() method. This
method is used to resume a thread which was suspended using suspend()
method. This method allows the suspended thread to start again.
Example
}
}
Output:
Thread-0
1
Dambal Sir (Sangola College,Sangola) 27
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4
Networking in Java
Introduction
Networking Terminology
ii) Protocol
A protocol is basically a set of rules and guidelines which provides the
instructions to send request and receive response over the network.
For example: TCP, UDP, SMTP, FTP etc.
v) Socket
Socket is a listener through which computer can receive requests and
responses. It is an endpoint of two way communication link. Every server or
programs runs on the different computers that has a socket and is bound to
the specific port number.
URL stands for Uniform Resourse Locator. The URL provides the logically
understandable form of uniquely identifying the resource or address
information on the Internet.
The URL class provides a simple, concise API to access information over the
Internet.
Method Description
String Returns the authority part of the URL.
getAuthority()
int defaultPort() Returns the default port number of the protocol
associated with given URL.
String getFile() Returns the file name of the given URL.
String getHost() Returns the host name of the URL.
String getPath() Returns the complete path of the given URL.
int getPort() Returns the port number of the given URL. If it is not
applicable, it returns -1.
String getQuery() Returns the query part of the given URL.
String getProtocol() Returns the name of the protocol of the given URL.
Following program shows the different methods of URL class:
import java.net.*;
public class URLDemo
{
public static void main(String args[]) throws MalformedURLException
Dambal Sir (Sangola College,Sangola) 29
{
URL url = new URL("http://www.google.com/java.htm");
System.out.println("URL: " + url.toString());
System.out.println("Protocol: "+url.getProtocol());
System.out.println("path: " + url.getPath());
System.out.println("Port: "+url.getPort());
System.out.println("Host: "+url.getHost());
System.out.println("Authority: " + url.getAuthority());
System.out.println("File: "+url.getFile());
System.out.println("Query: "+url.getQuery());
System.out.println("HashCode: "+url.hashCode());
System.out.println("External form: "+url.toExternalForm());
}
}