1 WAY User Defined Exception Handling(Our Throw Our Catch Exception Handling)
CODING:
CODING:
CODING:
import javax.swing.JOptionPane;
class sum
{
public static void main(String [] args)
{
int sum=0,num=0;
try
{
String n=JOptionPane.showInputDialog(null,"Enter A Number...");
if((int)(n.charAt(0))<48 || (int)(n.charAt(0))>57) //Check User Input a Number or String
{
throw new InputStringException(n);
}
else
{
num=Integer.parseInt(n);
System.out.println("NUMBER:"+num);
for(int i=0;i<n.length();i++)
{
sum=sum+(num%10);
num=num/10;
}
System.out.print("SUM OF "+n+" is:"+sum);
}
}
catch(InputStringException e)
{
System.out.print("Error:: " + e.getMessage());
}
}
}
class InputStringException extends Exception
{
InputStringException(String msg)
{
super(msg + " Not a Numer");
}
}
2 WAY Built In Exception Handlingclass sum
{
public static void main(String [] args)
{
int sum=0,num=0;
try
{
String n=JOptionPane.showInputDialog(null,"Enter A Number...");
if((int)(n.charAt(0))<48 || (int)(n.charAt(0))>57) //Check User Input a Number or String
{
throw new InputStringException(n);
}
else
{
num=Integer.parseInt(n);
System.out.println("NUMBER:"+num);
for(int i=0;i<n.length();i++)
{
sum=sum+(num%10);
num=num/10;
}
System.out.print("SUM OF "+n+" is:"+sum);
}
}
catch(InputStringException e)
{
System.out.print("Error:: " + e.getMessage());
}
}
}
class InputStringException extends Exception
{
InputStringException(String msg)
{
super(msg + " Not a Numer");
}
}
CODING:
import java.util.Scanner;
import java.lang.NumberFormatException;
class sum
{
public static void main(String [] args)
{
Scanner s=new Scanner(System.in);
int sum=0,num=0;
try
{
System.out.print("Input Number:");
String temp=s.nextLine();
num=Integer.parseInt(temp);
for(int i=0;i<temp.length();i++)
{
sum=sum+(num%10);
num=num/10;
}
System.out.println("NUMBER:"+temp);
System.out.print("SUM OF "+temp+" is:"+sum);
}
catch(NumberFormatException e)
{
System.out.print("Error:: Enter Only Numeric Value");
}
}
}
import java.lang.NumberFormatException;
class sum
{
public static void main(String [] args)
{
Scanner s=new Scanner(System.in);
int sum=0,num=0;
try
{
System.out.print("Input Number:");
String temp=s.nextLine();
num=Integer.parseInt(temp);
for(int i=0;i<temp.length();i++)
{
sum=sum+(num%10);
num=num/10;
}
System.out.println("NUMBER:"+temp);
System.out.print("SUM OF "+temp+" is:"+sum);
}
catch(NumberFormatException e)
{
System.out.print("Error:: Enter Only Numeric Value");
}
}
}
Comments
Post a Comment