Handling Exception in java

Previous
Next

Handling Exception:

  • Try block contains doubtful code that raises exception.
  • When exception raises, try block throws exception object to catch block.
  • Catch block collects the exception object and handles.
  • If no exception in try block, catch block will not execute

Syntax:

try
{
	1. Doubtful code that raises exception
	2. Related code to exception
}
catch(Exception_type  var)
{
	Handling logic...
}

Code Program:

import java.util.Scanner ;
import java.util.InputMismatchException ;
class ReadInt
{
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("Enter an integer : ");
		try
		{
			int x = scan.nextInt(); // doubtful code
			System.out.println("Integer value is : " + x);
		}
		catch (InputMismatchException obj)
		{
			System.out.println("Exception : Invalid input");
		}
	}
}
  • We can handle the exception by collecting the exception object into its Parent type variable also.
  • This concept is called Object up casting.
class ReadInt
{
	public static void main(String[] args) 
	{
		Scanner scan = new Scanner(System.in);
		System.out.print("Enter an integer : ");
		try
		{
			int x = scan.nextInt();
			System.out.println("Integer value is : " + x);
		}
		// catch (InputMismatchException obj)
		// catch (RuntimeException obj)
		// catch (Exception obj)
		catch (Throwable obj)
		{
			System.out.println("Exception : Invalid input");
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form