Table of Contents
To begin with, Exception Handling in Java deals with error this occurs when the program is executed. It can also be mentioned as an error that disrupts the normal flow of the program. Experienced and beginners both encounter this problem, and Java offers an object-oriented way to solve the errors; this is known as exception handling.
Further talking about, Exception Handling In Java which occurs during runtime errors and does occur for different reasons. Network connectivity issues, Wrong input data, calling a non-existent file, exceeding the memory limits of the Java virtual machine—there are also various types of Java exceptions, such as those that occur at run time, can’t be handled during compilation time, etc.
Types
Firstly Exception Handling is of two types: user-defined exceptions and built-in exceptions. The built-in exception has two types: checked and unchecked exceptions.
Checked exceptions | Unchecked exceptions |
This shows at compile time | This shows while executing the program |
The compiler identifies this type of exception | Because the compiler doesn’t identify this type of exception |
It can be solved during compilation time | It cannot be identified during compilation time |
Ex: IO Exception | Ex: Null pointer Exception |
There are various types of exception handling that fall under checked and unchecked exceptions. Now let’s see types under Unchecked Exception
1. Null pointer exception
When you call a variable whose value is zero or null, you’ll get a null pointer exception.
Below is a sample code
Below is a sample code
class nullpointerexception
{
public static void main()
{
String s = null;
System.out.println(s.length());
}
}
Output:
java. lang.NullPointerException
The value of the above variable is null and hence we get a null pointer Exception
2. Arithmetic Exception
This type of error occurs when you attempt to run the wrong mathematical operation through code. Under exception Handling in Java, this error is the only one that overlaps with mathematics.
Ex: Divide any number by zero
Below is a sample code:
public class ExceptionTest {
public static void main(String[] args) {
try {
int divbyzero = 1/0;
}
catch (ArithmeticException ex) {
ex.printStackTrace();
System.out.println (ERROR: Divide by zero")
Output:
The above code is showing an arithmetic error.
3. Array Index Out of Bounds Exception
Few of the Exception Handling In java deal with value. This error occurs when you process an array but call a value in the array which doesn’t exist in the particular array
Below is a sample code:
public class Example
{ public void processArray()
{ List names = new ArrayList<>(); names.add("Eric"); names.add("Sydney");
return names. get(5); } }
output:
ArrayIndexOutOfBoundsException
The code gives you the above error because you are calling a value that doesn’t exist.
4. Runtime exception
If any kind of exception arises during the execution of the program, it is a Runtime exception
Below is a sample code
public class Runtime_Excp_Ex { public void Demo_Runtime_Exception () { throw new Running_Exception(); } public static void main(String[] args) { try { new Running_Exception().Demo_Runtime_Exception(); } catch(Exception excpn) { System.out.println(excpn.getClass().getName()); } } } class Running_Exception extends RuntimeException { public Running_Exception() { super(); } public void Demo_Runtime_Exception() { throw new Running_Exception(); }
Output:
The error shows during execution only
5. Illegal thread state exception
This Exception Handling In java is quite unique as it attempts to show the status of the program. Suppose you attempt to start a thread that is already in running mode and executing its functions It gives you an exception called the illegal thread state exception.
Below is a Sample code:
public class MyThread extends Thread // Creating MyThread class that is extending the Thread class
{
public void run()
{
for (int i = 0; i < 3 ; i++)
{
System.out.println(i);
}
}
public static void main(String args[])
{
//In main() method, creating a thread object
MyThread th = new MyThread();
Stating the thread
th.start();
System.out.println("Alive is Awesome");
starting the thread again when it's already running, causing an IllegalThreadStateException.
th.start();
output:
Illegal thread state exception
Checked Exceptions
1. IO Exception
This kind of exception occurs while reading file directories and streams. Suppose you are calling a file ‘input.txt, which has not been declared, then such an exception. Under Exception Handling in Java, this exception deals with name of the files and directories.
Sample code:
import java.io.*;
// Example of FileNotFoundException
class Test{
public static void main(String[] args) {
// Creating an instance of FileReader class
FileReader fileReader = new FileReader("input.txt");
System.out.println(fileReader.read());
fileReader.close();
}
}
Output:
Main.java:7: error: unreported exception FileNotFoundException must be caught or declared to be thrown
FileReader fileReader = new FileReader(“input.txt”);
^
Main.java:8: error: unreported exception IOException must be caught or declared to be thrown
System.out.println(fileReader.read());
^
Main.java:9: error: unreported exception IOException must be caught or declared to be thrown
fileReader.close();
^
It is showing IO Exception
2. Class not found Exception
This Exception occurs when you are calling a class that does not exist.
Sample code:
// Java Program to Handle Checked Exception
Importing required classes
import java.io.*;
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Calling the class gfg, which is not present in the
// current class temp instance of calling class
Class temp = Class.forName("gfg");
It will throw ClassNotFoundException
}
}
Output:
Here we are calling it ‘gfg’ instead of ‘GFG’.
3. File not Found Exception
This Exception arises when you try to read data from a particular file under a particular class, but such a file doesn’t exist under the constructor, and this error is shown. Under Exception Handling In Java, this shows how careful you must be whenever you call a class.
Sample code:
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo {
public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
output:
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
4. no such method Exception
This Exception arises when we try to access elements from a set or Hash table that doesn’t have any elements.
Sample code:
// Java program to demonstrate NoSuchElementException
public class NoSuchElementException_Demo {
public static void main(String[] args)
{
Set exampleleSet = new HashSet();
Hashtable exampleTable = new Hashtable();
exampleleSet.iterator().next();
//accessing Set
exampleTable.elements().nextElement();
//accessing Hashtable
// This throws a NoSuchElementException as there are
// no elements in Set and HashTable and we are
// trying to access elements
}
}
Output:
no such method Exception
Henry Harvin Java course
Batch | Mode | Price | To enroll |
starts Every week | online | 65000 | Enroll here |
Why Henry Harvin?
Video URL:
1. Recognized for its quality by the top-most publishers like Hindustan Times, Business World, Statesman, etc.,
2. Affiliated and accredited by AAEFL, AAPC, Asian International University, MSME, Startup India, and more.
3. Therefore Awarded as the best corporate training program by Entrepreneur Education Innovation.
4. Additionally, the learners gain access to job support for its excellent networking.
Recommended Reads
Conclusion:
Java is a powerful programming language this is the base of many software we use in our daily life. Accordingly, Exception Handling In java which we discussed in this blog helps a programmer who finds himself/herself with a lot of errors. As a final point knowing these first handed will be easy to Identify, rectify and further move on to the next program.
FAQs
The exception is an error that arises in Java programming. For this reason, It can also be said as it disrupts the normal flow of programming
The error under this exception arises when the program is executed before we wouldn’t be able to identify it.
When you want to multiply a number by n number of times Ex: 25 multiplied 8 times you will get your answer. However, if you try to know the 25 multiplied by 45 in the square root without mentioning any number in the square root then an arithmetic error arises.
Eg: 25()x45