Saturday, 25 December 2021

Handling Exceptions in Java

 An Exception is a condition that is caused by a runtime error in the program when the java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it.

Java provides five keywords - try, catch, throw, finally, throws to handle run time errors. When the java interpreter encounters an exception it will display a message for the cause of exception ( throws the exception) if we want the program continue with the execution of remaining code, then you should try to catch the exception object thrown by the error condition and provide an appropriate handler. This task is known as exception handling and the following steps are performed while handling java runtime errors.

  1. Find the problem ( hit the exception)
  2. Inform that a error has occurred ( Throw the exception)
  3. Receive the error information (Catch the exception)
  4. Tale correct action ( Handle the exception)

Syntax for Exception Handling in Java

  The basic syntax for exception handling are throwing exception and catching it.


Java uses a keyword 'try' to write a block of code that may cause an error and throw an exception.

A catch block defined by the keyword 'catch' catches the exception thrown by the try block. The catch block is written immediately after the try block.

try

{

statements;

}catch(Exception e)

{

statements;

}

The try block can have one or more statements that cloud operate an exception. If any one statement generates an exception, the remaining statements in the block are skipped and execution jumps to catch block i.e placed next to the try-block. Every try block should be followed by at least one catch statement otherwise compile time error will occur.

The following java program shows how to handle an exception using try-catch

class JavaErrorDemo1 
{
	public static void main(String[] args) 
	{
		int a=10,b=5,c=5;
		int x,y;
		try
		{
		  x=a/(b-c);	
		}
		catch(ArithmeticException ex)
		{
			System.out.println("Division by zero");
		}
		y=a/(b+c);
		System.out.println("Value of Y is="+ y);
	}
}

Output

D:\java examples>javac JavaErrorDemo1.java
D:\java examples>java JavaErrorDemo1
Division by zero
Value of Y is=1

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.

Find Us On Facebook

Computer Basics

More

C Programming

More

Java Tutorial

More

Data Structures

More

MS Office

More

Database Management

More
Top