Handle unknown Exception

Advertisements

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 Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements