Handle unknown Exception


Prev Tutorial Next Tutorial

How to Handle unknown Exception

Whenever developer do not known what type of exception is going to be raised in the try block is known as unknown Exception. Java support three mechanism to handle unknown Exception.

  • Using Exception class
  • Using printStackTrace()
  • Using getMessage()

Using Exception class

It is a super class of all checked or unchecked Exception classes can be used to handle any type of Exception raised in the try block.

Syntax

try
{
......
......
}
catch(Exception e)
{
System.err.println(e);
}

Example

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.err.println(e);
}	
}
}
using exception class

Exception class object display two things

  • Exception class name which is raised in try block
  • Exception message

Using printStackTrace()

It is a predefined method of throwable class used to display the three properties of Exception.

  • Exception class name
  • Exception message
  • Line number at which Exception is raised

Syntax

try
{
.....
.....
}
catch(Exception e)
{
e.printStackTrace()
}

getMessage()

It is also a predefined method of throwable class used to get the system defined error message(only message) of an Exception which is raised in try block.

Syntax

try
{
.....
.....
}
catch(Exception e)
{
String msg=e.getMessage();
System.out.println(msg);
}

Example

import java.util.*;
class ExceptionDemo 
{
public static void main(String[] args) 
{
int a, b, ans=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any two numbers :");
try
{
	a=s.nextInt();
	b=s.nextInt();
	ans=a/b;
	System.out.println("Result: "+ans);
}
catch(Exception e)
{
String msg=e.getMessage();
System.out.println(msg);
}
}
}
getmessage

Example

import java.util.*;
class ExceptionDemo 
{
public static void main(String[] args) 
{
int a, b, ans=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter any two numbers :");
try
{
	a=s.nextInt();
	b=s.nextInt();
	ans=a/b;
	System.out.println("Result: "+ans);
}
catch(Exception e)
{
//String msg=e.printStackTrace();
//System.out.println(e.printStackTrace());
e.printStackTrace();
}
}
}
printstacktrace
Prev Tutorial Next Tutorial

Google Advertisements
Download Projects

Google Adsense Advertisements

Buy 3 Year Old Domain, Tutorialday.com, SeosmoTools.com @$200

Buy This Ad Space @$50 per Month, Ad Size 300X250 Contact on: hitesh.xc@gmail.com WhatsApp no. 8882538826

Yahoo Advertisements