Pages

Create exception handling


In this post, i want to share with you about how to create our own exception handling. Sometime when we build our program, we want it to handle certain mistake or exception that not exist in java predefined exception class.For example we want to control user from put negative integer value. Complete source code below will show you, how you can create an exception class that avoid user from put negative integer value.

*************************************************************
COMPLETE SOURCE CODE FOR : NegativeIntegerException.java
*************************************************************


import java.util.Scanner;

public class NegativeIntegerException extends RuntimeException
{
public void checkNumber(int a)
{
if(a<0)
{
throw new NegativeIntegerException();
}
}

public static void main(String[]args)
{
Scanner scanUserInput=new Scanner(System.in);
NegativeIntegerException nie=new NegativeIntegerException();
boolean b=true;
while(b)
{
System.out.println("Put an integer");
System.out.println("Put 0 EXIT");
int c=scanUserInput.nextInt();
if(c==0)
{
b=false;
}
else
{
try
{
nie.checkNumber(c);
System.out.println("YOUR NUMBER IS : "+c);
}
catch(NegativeIntegerException exception)
{
System.out.println("<<PLEASE PUT ONLY POSITIVE INTEGER!!!>>");
}
}
}
}
}


*************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************
Related Posts Plugin for WordPress, Blogger...