Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

Know all about Socket Programming in Java

Socket programming in Java is used for communication between the applications that are
running on different JRE. It can be either connection-oriented or connectionless. On the
whole, a socket is a way to establish a connection between a client and a server. In this
article, I will tell you all about Socket Programming.

Below topics are covered in this article:

 What is Socket Programming in Java?


 What is a Socket in Java?
 Client Side Programming
 Server Side Programming

What is Socket Programming in Java?


Socket programming is a way of connecting two nodes on a network to communicate with
each other. One socket (node) listens on a particular port at an IP, while
other socket reaches out to the other in order to form a connection.

The server forms the listener socket while the client reaches out to the server. Socket and
Server Socket classes are used for connection-oriented socket programming.

Now let’s understand the core concept of Socket Programming i.e. a socket.

What is a Socket in Java?


A socket in Java is one endpoint of a two-way communication link between two programs
running on the network. A socket is bound to a port number so that the TCP layer can identify
the application that data is destined to be sent to.
An endpoint is a combination of an
IP address and a port number. The package in the Java platform provides a class, Socket that
implements one side of a two-way connection between your Java program and another
program on the network. The class sits on top of a platform-dependent implementation, hiding
the details of any particular system from your Java program. By using the class instead of
relying on native code, your Java programs can communicate over the network in a platform-
independent fashion.

Now that you know, what is Socket in Java, let’s move further and understand how does client
communicates with the server and how the server responds back.

Client Side Programming


In the case of client-side programming, the client will first wait for the server to start. Once the
server is up and running, it will send the requests to the server. After that, the client will wait
for the response from the server. So, this is the whole logic of client and server
communication. Now let’s understand the client side and server side programming in detail.

In order to initiate a clients request, you need to follow the below-mentioned steps:

1. Establish a Connection

Java Certification Training Course

 Instructor-led Sessions
 Real-life Case Studies
 Assignments
 Lifetime Access

Explore Curriculum
The very first step is to establish a socket connection. A socket connection implies that the
two machines have information about each other’s network location (IP Address) and TCP
port.

You can create a Socket with the help of a below statement:

Socket socket = new Socket(“127.0.0.1”, 5000)

 Here, the first argument represents the IP address of Server.


 The second argument represents the TCP Port. (It is a number that represents which
application should run on a server.)

2. Communication

In order to communicate over a socket connection, streams are used for both input and output
the data. After establishing a connection and sending the requests, you need to close the
connection.

3. Closing the connection

The socket connection is closed explicitly once the message to the server is sent.

Now let’s see how to write a Java program to implement socket connection at client side.

1 // A Java program for a ClientSide


import java.net.*;
2
import java.io.*;
3 public class ClientProgram
4 {
5 // initialize socket and input output streams
6 private Socket socket = null;
private DataInputStream input = null;
7 private DataOutputStream out = null;
8 // constructor to put ip address and port
9 public Client(String address, int port)
10 {
11 // establish a connection
try
12 {
13 socket = new Socket(address, port);
14 System.out.println("Connected");
15 // takes input from terminal
input = new DataInputStream(System.in);
16 // sends output to the socket
17 out = new DataOutputStream(socket.getOutputStream());
18 }
19 catch(UnknownHostException u)
20 {
System.out.println(u);
21 }
22 catch(IOException i)
23 {
24 System.out.println(i);
25 }// string to read message from input
String line = "";
26 // keep reading until "Over" is input
27 while (!line.equals("Over"))
28 {
29
30
31
32
33
34 try
35 {
36 line = input.readLine();
out.writeUTF(line);
37 }
38 catch(IOException i)
39 {
40 System.out.println(i);
41 }
}
42 // close the connection
43 try
44 {
45 input.close();
out.close();
46
socket.close();
47 }
48 catch(IOException i)
49 {
50 System.out.println(i);
}
51 }
52 public static void main(String args[]) {
53 Client client = new Client("127.0.0.1", 5000);
54 }
55 }
56
57
58
59
60
Now, let’s implement server-side programming and then arrive at the output.

Server Side Programming


Basically, the server will instantiate its object and wait for the client request. Once the client
sends the request, the server will communicate back with the response.

In order to code the server-side application, you need two sockets and they are as follows:

 A ServerSocket which waits for the client requests (when a client makes a new
Socket())
 A plain old socket for communication with the client.

After this, you need to communicate with the client with the response.

Communication

getOutputStream() method is used to send the output through the socket.


Close the Connection

It is important to close the connection by closing the socket as well as input/output streams
once everything is done.

Now let’s see how to write a Java program to implement socket connection at server side.

1 // A Java program for a Serverside


import java.net.*;
2
import java.io.*;
3 public class ServerSide
4 {
5 //initialize socket and input stream
6 private Socket socket = null;
private ServerSocket server = null;
7 private DataInputStream in = null;
8 // constructor with port
9 public Server(int port)
10 {
11 // starts server and waits for a connection
try{
12 server = new ServerSocket(port);
13 System.out.println("Server started");
14 System.out.println("Waiting for a client ...");
15 socket = server.accept();
System.out.println("Client accepted");
16 // takes input from the client socket
17 in = new DataInputStream(
18 new BufferedInputStream(socket.getInputStream()));
19 String line = "";
20 // reads message from client until "Over" is sent
while (!line.equals("Over"))
21 {
22 try
23 {
24 line = in.readUTF();
25 System.out.println(line);
26  
27  
28  
}
29 catch(IOException i)
30 {
31 System.out.println(i);
32 }
}
33 System.out.println("Closing connection");
34 // close connection
35 socket.close();
36 in.close();
37 }
catch(IOException i){
38 System.out.println(i);
39 }
40 }
41 public static void main(String args[]){
Server server = new Server(5000);
42
}
43 }
44
45
46
47
48
49
50
51
52
After configuring both client and server end, you can execute  the server side program first.
After that, you need to run client side program and send the request. As soon as the request
is sent from the client end, server will respond back. Below snapshot represents the same.

1. When you run the server side script, it will start and wait for the client to get started.

2. Next, the client will get connected and inputs the request in the form of a string.

3. When the client sends the request, the server will respond back.

Java Certification Training Course

Weekday / Weekend BatchesSee Batch Details

That’s how you need to execute a socket program in Java. You can also execute these
programs on a terminal window or a command prompt.
Java Read Files
Read a File
In the previous chapter, you learned how to create and write to a file.

In the following example, we use the Scanner class to read the contents of the text
file we created in the previous chapter:

Example
import java.io.File; // Import the File class

import java.io.FileNotFoundException; // Import this class to handle errors

import java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {

public static void main(String[] args) {

try {

File myObj = new File("filename.txt");

Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine();

System.out.println(data);

myReader.close();

} catch (FileNotFoundException e) {

System.out.println("An error occurred.");

e.printStackTrace();

}
The output will be:

Files in Java might be tricky, but it is fun enough!


Run Example »

Get File Information


To get more information about a file, use any of the File methods:

Example
import java.io.File; // Import the File class

public class GetFileInfo {


public static void main(String[] args) {

File myObj = new File("filename.txt");

if (myObj.exists()) {

System.out.println("File name: " + myObj.getName());

System.out.println("Absolute path: " + myObj.getAbsolutePath());

System.out.println("Writeable: " + myObj.canWrite());

System.out.println("Readable " + myObj.canRead());

System.out.println("File size in bytes " + myObj.length());

} else {

System.out.println("The file does not exist.");

The output will be:

File name: filename.txt


Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Run Example »
Note: There are many available classes in the Java API that can be used to read and
write files in Java: FileReader, BufferedReader, Files, Scanner,
FileInputStream, FileWriter, BufferedWriter, FileOutputStream , etc. Which one
to use depends on the Java version you're working with and whether you need to
read bytes or characters, and the size of the file/lines etc.

Tip: To delete a file, read our Java Delete Files chapter.

Java Threads
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.

Creating a Thread
There are two ways to create a thread.

It can be created by extending the Thread class and overriding its run() method:

Extend Syntax
public class Main extends Thread {

public void run() {

System.out.println("This code is running in a thread");

Another way to create a thread is to implement the Runnable interface:

Implement Syntax
public class Main implements Runnable {
public void run() {

System.out.println("This code is running in a thread");

Running Threads
If the class extends the Thread class, the thread can be run by creating an instance
of the class and call its start() method:

Extend Example
public class Main extends Thread {

public static void main(String[] args) {

Main thread = new Main();

thread.start();

System.out.println("This code is outside of the thread");

public void run() {

System.out.println("This code is running in a thread");

Try it Yourself »

If the class implements the Runnable interface, the thread can be run by passing an


instance of the class to a Thread object's constructor and then calling the
thread's start() method:

Implement Example
public class Main implements Runnable {

public static void main(String[] args) {

Main obj = new Main();


Thread thread = new Thread(obj);

thread.start();

System.out.println("This code is outside of the thread");

public void run() {

System.out.println("This code is running in a thread");

Try it Yourself »
Differences between "extending" and "implementing" Threads

The major difference is that when a class extends the Thread class, you cannot
extend any other class, but by implementing the Runnable interface, it is possible to
extend from another class as well, like: class MyClass extends OtherClass
implements Runnable.

Concurrency Problems
Because threads run at the same time as other parts of the program, there is no way
to know in which order the code will run. When the threads and main program are
reading and writing the same variables, the values are unpredictable. The problems
that result from this are called concurrency problems.

Example
A code example where the value of the variable amount is unpredictable:

public class Main extends Thread {

public static int amount = 0;

public static void main(String[] args) {

Main thread = new Main();

thread.start();

System.out.println(amount);
amount++;

System.out.println(amount);

public void run() {

amount++;

Try it Yourself »

To avoid concurrency problems, it is best to share as few attributes between threads


as possible. If attributes need to be shared, one possible solution is to use
the isAlive() method of the thread to check whether the thread has finished running
before using any attributes that the thread can change.

Example
Use isAlive() to prevent concurrency problems:

public class Main extends Thread {

public static int amount = 0;

public static void main(String[] args) {

Main thread = new Main();

thread.start();

// Wait for the thread to finish

while(thread.isAlive()) {

System.out.println("Waiting...");

// Update amount and print its value

System.out.println("Main: " + amount);

amount++;

System.out.println("Main: " + amount);


}

public void run() {

amount++;

Generics in Java
Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and
user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is
possible to create classes that work with different data types. An entity such as class, interface,
or method that operates on a parameterized type is a generic entity.

Why Generics?

The Object is the superclass of all other classes, and Object reference can refer to any object.
These features lack type safety. Generics add that type of safety feature. We will discuss that
type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like HashSet, ArrayList,
HashMap, etc., use generics very well. There are some fundamental differences between the
two approaches to generic types. 

Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic method has type
parameters that are cited by actual type. This allows the generic method to be used in a more
general way. The compiler takes care of the type of safety which enables programmers to code
easily since they do not have to perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one or more parameters, are
known as parameterized classes or parameterized types.

Generic Class 

Like C++, we use <> to specify parameter types in generic class creation. To create objects of a
generic class, we use the following syntax. 
// To create an instance of generic class
BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.
 Java

// Java program to show working of user defined

// Generic classes

  

// We use < > to specify Parameter type

class Test<T> {

    // An object of type T is declared

    T obj;

    Test(T obj) { this.obj = obj; } // constructor

    public T getObject() { return this.obj; }

  

// Driver class to test above

class Main {

    public static void main(String[] args)

    {

        // instance of Integer type

        Test<Integer> iObj = new Test<Integer>(15);

        System.out.println(iObj.getObject());

  

        // instance of String type

        Test<String> sObj
            = new Test<String>("GeeksForGeeks");

        System.out.println(sObj.getObject());

    }

Output
15
GeeksForGeeks
We can also pass multiple Type parameters in Generic classes. 

 Java

// Java program to show multiple

// type parameters in Java Generics

  // We use < > to specify Parameter type

class Test<T, U>

    T obj1;  // An object of type T

    U obj2;  // An object of type U

      // constructor

    Test(T obj1, U obj2)

    {

        this.obj1 = obj1;

        this.obj2 = obj2;

    }
    // To print objects of T and U

    public void print()

    {

        System.out.println(obj1);

        System.out.println(obj2);

    }

}  

// Driver class to test above

class Main

    public static void main (String[] args)

    {

        Test <String, Integer> obj =

            new Test<String, Integer>("GfG", 15);

          obj.print();

    }

Output
GfG
15

Generic Functions: 

We can also write generic functions that can be called with different types of arguments based
on the type of arguments passed to the generic method. The compiler handles each method.
 Java

// Java program to show working of user defined

// Generic functions

  

class Test {

    // A Generic method example

    static <T> void genericDisplay(T element)

    {

        System.out.println(element.getClass().getName()

                           + " = " + element);

    }

  

    // Driver method

    public static void main(String[] args)

    {

        // Calling generic method with Integer argument

        genericDisplay(11);

  

        // Calling generic method with String argument

        genericDisplay("GeeksForGeeks");

  

        // Calling generic method with double argument


        genericDisplay(1.0);

    }

Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0

Generics Work Only with Reference Types: 

When we declare an instance of a generic type, the type argument passed to the type parameter
must be a reference type. We cannot use primitive data types like int, char.
Test<int> obj = new Test<int>(20);
The above line results in a compile-time error that can be resolved using type wrappers to
encapsulate a primitive type. 
But primitive type arrays can be passed to the type parameter because arrays are reference
types.
ArrayList<int[]> a = new ArrayList<>();

Generic Types Differ Based on Their Type Arguments: 

Consider the following Java code.

 Java

// Java program to show working

// of user-defined Generic classes

  

// We use < > to specify Parameter type

class Test<T> {
    // An object of type T is declared

    T obj;

    Test(T obj) { this.obj = obj; } // constructor

    public T getObject() { return this.obj; }

  

// Driver class to test above

class Main {

    public static void main(String[] args)

    {

        // instance of Integer type

        Test<Integer> iObj = new Test<Integer>(15);

        System.out.println(iObj.getObject());

  

        // instance of String type

        Test<String> sObj

            = new Test<String>("GeeksForGeeks");

        System.out.println(sObj.getObject());

        iObj = sObj; // This results an error

    }

Output: 
error:
incompatible types:
Test cannot be converted to Test
Even though iObj and sObj are of type Test, they are the references to different types because
their type parameters differ. Generics add type safety through this and prevent errors.

Type Parameters in Java Generics

The type parameters naming conventions are important to learn generics thoroughly. The
common type parameters are as follows:
 T – Type
 E – Element
 K – Key
 N – Number
 V – Value

Advantages of Generics: 

Programs that use Generics has got many benefits over non-generic code. 
1. Code Reuse: We can write a method/class/interface once and use it for any type we want.
2. Type Safety: Generics make errors to appear compile time than at run time (It’s always
better to know problems in your code at compile time rather than making your code fail at run
time). Suppose you want to create an ArrayList that store name of students, and if by mistake
the programmer adds an integer object instead of a string, the compiler allows it. But, when we
retrieve this data from ArrayList, it causes problems at runtime.
 Java

// Java program to demonstrate that NOT using

// generics can cause run time exceptions

  

import java.util.*;

  

class Test

{
    public static void main(String[] args)

    {

        // Creatinga an ArrayList without any type specified

        ArrayList al = new ArrayList();

  

        al.add("Sachin");

        al.add("Rahul");

        al.add(10); // Compiler allows this

  

        String s1 = (String)al.get(0);

        String s2 = (String)al.get(1);

  

        // Causes Runtime Exception

        String s3 = (String)al.get(2);

    }

Output :
Exception in thread "main" java.lang.ClassCastException:
java.lang.Integer cannot be cast to java.lang.String
at Test.main(Test.java:19)

How do Generics Solve this Problem? 

When defining ArrayList, we can specify that this list can take only String objects.

 Java
// Using Java Generics converts run time exceptions into 

// compile time exception.

import java.util.*;

  

class Test

    public static void main(String[] args)

    {

        // Creating a an ArrayList with String specified

        ArrayList <String> al = new ArrayList<String> ();

  

        al.add("Sachin");

        al.add("Rahul");

  

        // Now Compiler doesn't allow this

        al.add(10); 

  

        String s1 = (String)al.get(0);

        String s2 = (String)al.get(1);

        String s3 = (String)al.get(2);

    }

}
Output: 
15: error: no suitable method found for add(int)
al.add(10);
^
3. Individual Type Casting is not needed: If we do not use generics, then, in the above
example, every time we retrieve data from ArrayList, we have to typecast it. Typecasting at
every retrieval operation is a big headache. If we already know that our list only holds string
data, we need not typecast it every time.
 Java

// We don't need to typecast individual members of ArrayList

  

import java.util.*;

  

class Test {

    public static void main(String[] args)

    {

        // Creating a an ArrayList with String specified

        ArrayList<String> al = new ArrayList<String>();

  

        al.add("Sachin");

        al.add("Rahul");

  

        // Typecasting is not needed

        String s1 = al.get(0);

        String s2 = al.get(1);
    }

4. Generics Promotes Code Reusability: With the help of generics in Java, we can write code
that will work with different types of data. For example,
public <T> void genericsMethod (T data) {...}
Here, we have created a generics method. This same method can be used to perform operations
on integer data, string data, and so on.
5. Implementing Generic Algorithms: By using generics, we can implement algorithms that
work on different types of objects, and at the same, they are type-safe too.
This article is contributed by Dharmesh Singh. If you like GeeksforGeeks and would like to
contribute, you can also write an article and mail your article to review-
team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help
other Geeks. Please write comments if you find anything incorrect, or you want to share more
information about the topic discussed above.

Exception Handling in Java


The classic definition of an exception is an event that occurs during the execution of a
program and that disrupts the normal flow of instructions. Java exceptions are specialized
events that indicate something bad has happened in the application, and the application
either needs to recover or exit.

Why handle Java exceptions?


Java exception handling is important because it helps maintain the normal, desired flow of
the program even when unexpected events occur. If Java exceptions are not handled,
programs may crash or requests may fail. This can be very frustrating for customers and if it
happens repeatedly, you could lose those customers.

The worst situation is if your application crashes while the user is doing any important
work, especially if their data is lost. To make the user interface robust, it is important to
handle Java exceptions to prevent the application from unexpectedly crashing and losing
data. There can be many causes for a sudden crash of the system, such as incorrect or
unexpected data input. For example, if we try to add two users with duplicate IDs to the
database, we should throw an exception since the action would affect database integrity.

Developers can predict many of the Java exceptions that a piece of code is capable of
throwing.
The best course of action is to explicitly handle those exceptions to recover from them
gracefully. As we will see ahead, programming languages provide ways to handle
exceptions starting from specific ones and moving toward the more generic ones. Java
exceptions that you cannot easily predict ahead of time are called unhandled exceptions. It’s
good to capture these too in order to gracefully recover. Tracking these Java exceptions
centrally offers visibility to your development team on the quality of the code and what
causes these errors so they can fix them faster.

Tracking Exceptions in Java


One thing that most experienced developers will agree with is that exceptions will happen in
your application, no matter how well you write your program. You cannot predict the
runtime environment entirely, especially that of your customer’s.

The standard practice is to record all events in the application log file. The log file acts as a
time machine helping the developer (or analyst) go back in time to view all the phases the
application went through and what led to the Java exception.

For small-scale applications, going through a log file is easy. However, enterprise
applications can serve thousands or even millions of requests per second. This makes
manual analysis too cumbersome because errors and their causes can be lost in the noise.
This is where error monitoring software can help by grouping duplicates and providing
summarized views of the top and most recent Java errors. They can also capture and
organize contextual data in a way that’s easier and faster than looking at logs.

How to handle exceptions in Java


Let's start with the basics of exception handling in Java before we move to more advanced
topics. The try-catch is the simplest method of handling exceptions. Put the code you
want to run in the try block, and any Java exceptions that the code throws are caught by
one or more catch blocks.

This method will catch any type of Java exceptions that get thrown. This is the simplest
mechanism for handling exceptions.
try {
// block of code that can throw exceptions
} catch (Exception ex) {
// Exception handler
}

Note: You can’t use a try block alone. The try block should be immediately followed either
by a catch or finally block.

Catching specific Java exceptions


You can also specify specific exceptions you would like to catch. This allows you to have
dedicated code to recover from those errors. For example, some Java errors returned from a
REST API are recoverable and others are not. This allows you to treat those conditions
separately.

A try block can be followed by one or more catch blocks, each specifying a different type.


The first catch block that handles the exception class or one of its superclasses will be
executed. So, make sure to catch the most specific class first.
try {
// block of code that can throw exceptions
} catch (ExceptionType1 ex1) {
// exception handler for ExceptionType1
} catch (ExceptionType2 ex2) {
// Exception handler for ExceptionType2
}

If an exception occurs in the try block, the exception is thrown to the first catch block. If


not, the Java exception passes down to the second catch statement. This continues until the
exception either is caught or falls through all catches.

The finally block


Any code that must be executed irrespective of occurrence of an exception is put in
a finally block. In other words, a finally block is executed in all circumstances. For
example, if you have an open connection to a database or file, use the finally block to
close the connection even if the try block throws a Java exception.
try {
// block of code that can throw exceptions
} catch (ExceptionType1 ex1) {
// exception handler for ExceptionType1
} catch (ExceptionType2 ex2) {
// Exception handler for ExceptionType2
} finally {
// finally block always executes
}

Handling uncaught or runtime Java


exceptions
Uncaught or runtime exceptions happen unexpectedly, so you may not have a try-
catch block to protect your code and the compiler cannot give you warnings either.
Thankfully, Java provides a powerful mechanism for handling runtime exceptions.
Every Thread includes a hook that allows you to set an UncaughtExceptionHandler. Its
interface declares the method uncaughtException(Thread t1, Throwable e1). It will
be invoked when a given thread t1 terminates due to the given uncaught exception e1.
Thread.setDefaultUncaughtExceptionHandler(new
Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t1, Throwable e1) {
// Exception handling code
}
});

Track, Analyze and Manage Java Errors


With Rollbar
Managing errors and Java exceptions in your code is challenging. It can make deploying
production code an unnerving experience. Being able to track, analyze, and manage errors
in real-time can help you to proceed with more confidence. Rollbar automates error
monitoring and triaging, making fixing Java errors easier than ever. Learn more
about Rollbar’s features for Java and then sign up for a free trial.

How to Throw Exceptions in Flutter

Exception Handling in Java


1. Exception Handling

2. Advantage of Exception Handling

3. Hierarchy of Exception classes

4. Types of Exception

5. Exception Example

6. Scenarios where an exception may occur


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that the normal flow of the application can be maintained.

In this tutorial, we will learn about Java exceptions, it's types, and the difference between
checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object
which is thrown at runtime.

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. Let's consider a scenario:

1. statement 1;  
2. statement 2;  
3. statement 3;  
4. statement 4;  
5. statement 5;//exception occurs  
6. statement 6;  
7. statement 7;  
8. statement 8;  
9. statement 9;  
10. statement 10;  

Suppose there are 10 statements in a Java program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.
However, when we perform exception handling, the rest of the statements will be executed.
That is why we use exception handling in Java
.
Do You Know?
o What is the difference between checked and unchecked exceptions?
o What happens behind the code int data=50/0;?
o Why use multiple catch block?
o Is there any possibility when the finally block is not executed?
o What is exception propagation?
o What is the difference between the throw and throws keyword?
o What are the 4 rules for using exception handling with method overriding?

Hierarchy of Java Exception classes


The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as
the unchecked exception. However, according to Oracle, there are three types of exceptions
namely:

1. Checked Exception
2. Unchecked Exception
3. Error

Difference between Checked and Unchecked Exceptions


1) Checked Exception

The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.

2) Unchecked Exception

The classes that inherit the RuntimeException are known as unchecked exceptions. For
example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table
describes each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. 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 doesn't throw an exception. It is always
used with method signature.

Java Exception Handling Example


Let's see an example of Java Exception Handling in which we are using a try-catch statement
to handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{  
2.   public static void main(String args[]){  
3.    try{  
4.       //code that may raise exception  
5.       int data=100/0;  
6.    }catch(ArithmeticException e){System.out.println(e);}  
7.    //rest code of the program   
8.    System.out.println("rest of the code...");  
9.   }  
10. }  
Test it Now

Output:

Exception in thread main java.lang.ArithmeticException:/ by zero


rest of the code...

In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch


block.

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

1. int a=50/0;//ArithmeticException  

2) A scenario where NullPointerException occurs

If we have a null value in any variable

, performing any operation on the variable throws a NullPointerException.

String s=null;  
1. System.out.println(s.length());//NullPointerException  

3) A scenario where NumberFormatException occurs

If the formatting of any variable or number is mismatched, it may result into


NumberFormatException. Suppose we have a string

variable that has characters; converting this variable into digit will cause NumberFormatException.
1. String s="abc";  
2. int i=Integer.parseInt(s);//NumberFormatException  

4) A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.

1. int a[]=new int[5];  
2. a[10]=50; //ArrayIndexOutOfBoundsException  

Java Exceptions Index


Java Try-Catch Block

Java Multiple Catch Block

Java Nested Try

Java Finally Block

Java Throw Keyword

Java Exception Propagation

Java Throws Keyword

Java Throw vs Throws

Java Final vs Finally vs Finalize

Java Exception Handling with Method Overriding

Java Custom Exceptions

Exception Handling with Method Overriding in Java


There are many rules if we talk about method overriding with exception handling.

Some of the rules are listed below:

o If the superclass method does not declare an exception


o If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception but it can declare unchecked
exception.
o If the superclass method declares an exception
o If the superclass method declares an exception, subclass overridden method can
declare same, subclass exception or no exception but cannot declare parent
exception.

If the superclass method does not declare an exception


Rule 1: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception.

Let's consider following example based on the above rule.

TestExceptionChild.java

1. import java.io.*;    
2. class Parent{   
3.   
4.   // defining the method   
5.   void msg() {  
6.     System.out.println("parent method");  
7.     }    
8. }    
9.     
10. public class TestExceptionChild extends Parent{    
11.   
12.   // overriding the method in child class  
13.   // gives compile time error  
14.   void msg() throws IOException {    
15.     System.out.println("TestExceptionChild");    
16.   }  
17.   
18.   public static void main(String args[]) {    
19.    Parent p = new TestExceptionChild();    
20.    p.msg();    
21.   }    
22. }    

Output:

Rule 2: If the superclass method does not declare an exception, subclass overridden method
cannot declare the checked exception but can declare unchecked exception.

TestExceptionChild1.java

1. import java.io.*;    
2. class Parent{    
3.   void msg() {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. class TestExceptionChild1 extends Parent{    
9.   void msg()throws ArithmeticException {    
10.     System.out.println("child method");    
11.   }    
12.   
13.   public static void main(String args[]) {    
14.    Parent p = new TestExceptionChild1();    
15.    p.msg();    
16.   }    
17. }   

Output:

If the superclass method declares an exception


Rule 1: If the superclass method declares an exception, subclass overridden method can declare
the same subclass exception or no exception but cannot declare parent exception.

Example in case subclass overridden method declares parent


exception
TestExceptionChild2.java

1. import java.io.*;    
2. class Parent{    
3.   void msg()throws ArithmeticException {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. public class TestExceptionChild2 extends Parent{    
9.   void msg()throws Exception {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]) {    
14.    Parent p = new TestExceptionChild2();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch (Exception e){}   
20.   
21.   }    
22. }     

Output:
Example in case subclass overridden method declares same
exception
TestExceptionChild3.java

1. import java.io.*;    
2. class Parent{    
3.   void msg() throws Exception {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. public class TestExceptionChild3 extends Parent {    
9.   void msg()throws Exception {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]){    
14.    Parent p = new TestExceptionChild3();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch(Exception e) {}    
20.   }    
21. }    

Output:

Example in case subclass overridden method declares subclass


exception
TestExceptionChild4.java

1. import java.io.*;    
2. class Parent{    
3.   void msg()throws Exception {  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. class TestExceptionChild4 extends Parent{    
9.   void msg()throws ArithmeticException {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]){    
14.    Parent p = new TestExceptionChild4();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch(Exception e) {}    
20.   }    
21. }    

Output:

Example in case subclass overridden method declares no exception


TestExceptionChild5.java

1. import java.io.*;    
2. class Parent {    
3.   void msg()throws Exception{  
4.     System.out.println("parent method");  
5.   }    
6. }    
7.     
8. class TestExceptionChild5 extends Parent{    
9.   void msg() {  
10.     System.out.println("child method");  
11.   }    
12.     
13.   public static void main(String args[]){    
14.    Parent p = new TestExceptionChild5();    
15.      
16.    try {    
17.    p.msg();    
18.    }  
19.    catch(Exception e) {}  
20.        
21.   }    
22. }     

Output:

Custom Exception

You might also like