Basic Java – 24 || Exception Handling using Try Catch.

Exceptions are the runtime error in a program encountered while execution.

Java Tutorials

Basically there are two type of Errors exist in any program.

  1. Compiler Error: These are the error in the code itself. It means syntax error. Few examples are given below:
    • a semicolon(;) missing at the end of the statement.
    • Grammatical error while using the java reserved keywords like String, int, Class, etc.
    • The code of blocks {} is not closed properly.
    • A method is called with invalid parameters.
    • Variables are used in programs without initialization.
    • The library files not present in the project which contains a specific class or method used in the program.
    • Even the compiler gives an error if it predicts that there could be a possible error that occurs during program execution. The compiler forces us to add in-build exceptions in the program. Like FileNotFoundException, IOException, etc.
  2. Run-time Error: On the other hand, run-time errors occurred during program execution. This can be happened due to the below reasons:
    • Incorrect program logic. Like, divide any number with 0.
    • The program goes to an infinite loop.
    • Invalid input value during execution.
    • Input or validation points not found during execution. like searching for an XPath that does not exist or not load.
    • Page loading timeout.

Different types of Exceptions

As exceptions are run-time errors in a program. But there are many exceptions caught by the compiler during coding and added to the program. This is known as Checked Exceptions. Few examples are given below:

  1. FileNotFoundException: When we are using file handling to read/write data.
  2. IOException: This can appear when we are using InputStreamReader Class to take user inputs.

All these are sub-class of the Exception class. Let’s learn about other types of exceptions in java.

ArithmeticException

Any run-time error which can’t be predict during compilation. Like dividing a numeric value with 0.

public static void main(String[] args) {
		
		int a=1;
		int b=0;
		System.out.println(a/b);
	}

Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
	at Sample.main(Sample.java:24)

ArrayIndexOutOfBoundsException

Suppose, we have declared an array with size 5. So, here we can use index value as 0 to 4 only. If we try to access the value using the index as less than 0 or greater than 4 it will throw an exception.

public static void main(String[] args) {
		
		int[] array=new int[5];
		array[0]=1;
		array[1]=2;
		array[2]=3;
		array[3]=4;
		array[4]=5;
		array[5]=6;
	}

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
	at Sample.main(Sample.java:25)

FileNotFoundException

When we are using File and FileInputStream objects for file handling compiler will throw this exception. This is a checked exception so the compiler will notify the programmer as an error and force to handle this exception.

Snapshot of the coding which shows the compile time error to handle FileNotFoundException.

We can use any option to fix this error either “Add throws declaration” or “Surround with try/catch“.

IOException

This is also a checked exception and will appear while using InputStreamReader and BufferedReader Classes and methods.

NullPointerException

Throws error if we are using any method or action on a variable that is pointing to a ‘null‘ value.

In the below code snippet we have used the charAt(1) method for both st1 and st2. But st2 will throw Exception as it is pointing to a null value.

public class Sample {
	public static void main(String[] args) {
		String st1="SampleClass";
		System.out.println("st1: "+st1.charAt(1));
		
		String st2=null;
		System.out.println("st2: "+st2.charAt(1));
	}
}

Output:
st1: a
Exception in thread "main" java.lang.NullPointerException
	at Sample.main(Sample.java:24)

Exception Handling using Try-Catch block

Till now we understand that exceptions can be a reason for unwanted termination of the program. So, to make our program error-free we have to take care of these exceptions and provide alternate execution paths to our program.

This can be done using the try-catch block and this process is known as Exception Handling.

try block: A try block contains the line of code that might throw an exception at run-time.

catch block: Each try block should have at least one or more catch block to handle the Exception.

public static void main(String[] args) {
		
		String st1="SampleClass";
		System.out.println("st1: "+st1.charAt(1));
		
		String st2=null;
		try
		{
			System.out.println("st2: "+st2.charAt(1));
		}
		catch(Exception e)
		{
			System.out.println("String variable st2 is pointing to 'null' value.");
			System.out.println("Exception is :"+e);
		}
		
		System.out.println("Program execution completed.");
	}

Output:
st1: a
String variable st2 is pointing to 'null' value.
Exception is :java.lang.NullPointerException
Program execution completed.

finally block: This is an optional block and is executed only after the try/catch block. In the above program, we could put the last line of code in the finally block.

public static void main(String[] args) {
	
		String st1="SampleClass";
		System.out.println("st1: "+st1.charAt(1));
		
		String st2=null;
		try
		{
			System.out.println("st2: "+st2.charAt(1));
		}
		catch(Exception e)
		{
			System.out.println("String variable st2 is pointing to 'null' value.");
			System.out.println("Exception is :"+e);
		}
		
		finally {
			System.out.println("Program execution completed.");
		}
}

Output:
st1: a
String variable st2 is pointing to 'null' value.
Exception is :java.lang.NullPointerException
Program execution completed.

Note: If we know which type of exception will occur in the future it is advisable to use specific Exception Classes like NullPointerException, FileNotFoundException, etc. But in case we don’t have any idea of this we could use the Exception class directly.

Using specific Exception Class

Let’s take an example of a program as mentioned below:

  1. Take two integer type variables a and b.
  2. Get inputs for these two variables via end-user at run-time using Scanner class.
  3. Divide both the values and store the result in the third variable.
  4. Print the result on the console.

The below program will run smoothly for the ideal scenario where inputs are in numeric form and greater than 0.

public class Sample {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		System.out.print("Enter Value of a: ");
		int a=sc.nextInt();
		
		System.out.print("\nEnter value of b: ");
		int b=sc.nextInt();
		
		int result=a/b;
		System.out.println("\nResult is = "+result);
	}
}

Output:
Enter Value of a: 10
Enter value of b: 5
Result is = 2

But if we give random user input it may throw an exception and terminates the program as mentioned below:

  1. b=0 | Gives ArithmeticException
  2. b=non-numeric value like character | Gives InputMismatchException

To handle such situations we can use multiple catch blocks for specific Exceptions with customized user messages.

public static void main(String[] args) {
		
		Scanner sc=new Scanner(System.in);
		int result=0;
		
		try
		{
		System.out.print("Enter Value of a: ");
		int a=sc.nextInt();
		
		System.out.print("\nEnter value of b: ");
		int b=sc.nextInt();
		
		result=a/b;
		}
		catch(InputMismatchException e1)
		{
			System.out.println("Please enter only numeric values as user input.");
			System.out.println(e1);
		}
		catch(ArithmeticException e2)
		{
			System.out.println("Value of b should be greater than 0.");
			System.out.println(e2);
		}
		
		System.out.println("\nResult is = "+result);
		System.out.println("Program execution finished.");
		
}

Output:
Enter Value of a: 6

Enter value of b: 0
Value of b should be greater than 0.
java.lang.ArithmeticException: / by zero

Result is = 0
Program execution finished.

Using ‘throw’ keyword

The ‘throw‘ keyword is used to generate exceptions forcefully. This means logically there is an exception but as per program requirement or flow, we can generate exceptions. Sometimes it is called an explicit exception.

public static void main(String[] args)
	{
		System.out.println("Example of 'throw' keyword");
		throw new ArrayIndexOutOfBoundsException();
	}

Output:
Example of 'throw' keyword
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
	at ExceptionExample2.main(ExceptionExample2.java:20)

Now we can use try-catch blocks to handle this exception as mentioned below program.

public static void main(String[] args)
	{
		
		System.out.println("Example of 'throw' keyword");
		try
		{
		throw new ArrayIndexOutOfBoundsException("User message: Explicit exception.");
		}
		catch(ArrayIndexOutOfBoundsException e)
		{
			System.out.println("Caught in catch block: "+e);
		}
		
		System.out.println("Program execution finish.");
	}

Output:
Example of 'throw' keyword
Caught in catch block: java.lang.ArrayIndexOutOfBoundsException: User message: Explicit exception.
Program execution finish.

Difference between throw and throws keyword

As we have seen in the above example ‘throw‘ keyword is used to throw explicit exceptions whether logically it occurs or not.

On the other hand ‘throws‘ keyword used for checked exceptions where the compiler predicts that exceptions may occur in the future.

Example of throws keyword.

As in the above example if we use “Add throws declaration” it will add “FileNotFoundException” along with the main() method. And it will throw exceptions if the file is not found at the given path.

public static void main(String[] args) throws FileNotFoundException
	{
		File f=new File("c://test.xlsx");
		FileInputStream fis=new FileInputStream(f);
	}

Java Basics:


Leave a Reply

Your email address will not be published. Required fields are marked *

Site Statistics

  • Users online: 0 
  • Visitors today : 0
  • Page views today : 0
  • Total visitors : 51,147
  • Total page view: 70,412

   YouTube ChannelQuora

            Ashok Kumar is working in an IT Company as a QA Consultant. He has started his career as a Test Trainee in manual testing in August 2010. Then he moves towards the automation testing after 4 years. He started learning JAVA and Selenium by self to get the knowledge of automation.

       While learning these tools and working on multiple projects, he found that sometimes people get stuck in live scenarios in their project and they have to do lots of RnD to get out of it. So he decided to start blogging only for such scenarios, where anyone facing any problem in their project, can ask any question or give a solution or you can say an alternate solution to achieve the goal successfully.

Later on, he observed that some people want to learn Java but they have few questions in their mind like how to start Java, whether we should go for the online or offline course. So he started writing tutorials on Java, Jira, Selenium, Excel etc.