Showing posts with label java exception handling. Show all posts
Showing posts with label java exception handling. Show all posts
java - Exception handling - sum of numebrs - NumberFormatException
/*
Write a java program for exception
handling:
To add two integers and raise exception
when any other character except number (0 – 9) is given as input.
*/
// Java Exception Handling
// Number format exception
import java.util.*;
class numberformatexceptions
{
public
static void main(String args[])
{
String
s1, s2;
Scanner
s = new Scanner(System.in);
try
{
System.out.print("Enter
first number : ");
s1
= s.next();
System.out.print("Enter
second number : ");
s2
= s.next();
int
x = Integer.parseInt(s1);
int
y = Integer.parseInt(s2);
System.out.print("Sum
= "+(x+y));
}
catch(Exception
e)
{
System.out.println(e)
;
}
}
}
Java - exception handling - sum of numbers - input mismatch exception
/*
Write a java program for exception
handling:
To add two integers and raise exception
when any other character except number (0 – 9) is given as input.
*/
// java Exception Handling
// input mismatch exception
import java.util.*;
class inputmismatchexceptions
{
public
static void main(String args[])
{
int
x, y;
Scanner
s = new Scanner(System.in);
try
{
System.out.print("Enter
first number : ");
x
= s.nextInt();
System.out.print("Enter
second number : ");
y
= s.nextInt();
System.out.print("Sum
= "+(x+y));
}
catch(Exception
e)
{
System.out.println(e)
;
}
}
}
Java user Defined Exception Handling - Hello Exception
/*
Write a java program for exception
handling:
To
create a user defined exception whenever user input the word "hello".
*/
// java Exception Handling
// user defined exception
import java.util.*;
class userdefinedexception extends
Exception
{
public
String toString()
{
return
("Hello Exception");
}
}
class UsrDefException
{
public
static void main(String args[])
{
String
str;
Scanner
s = new Scanner(System.in);
try
{
System.out.print("Enter
name : ");
str
= s.next().trim();
//
throw is used to create a new exception and throw it.
if(str.equalsIgnoreCase("HELLO"))
{
throw
new userdefinedexception();
}
else
System.out.print("Hello
"+str);
}
catch(userdefinedexception
e)
{
System.out.println(e)
;
}
}
}
/*
Sample output
D:\oopjava>javac UsrDefException.java
D:\oopjava>java UsrDefException
Enter name : asdf
Hello asdf
D:\oopjava>java UsrDefException
Enter name : hello
Hello Exception
D:\oopjava>
Java - exception Handling - user defined exception handling
// user defined exception
class userdefinedexception extends
Exception
{
int
a;
userdefinedexception(int
b)
{
a
= b;
}
public
String toString()
{
return
("Exception Number = "+a) ;
}
}
class JavaException
{
public
static void main(String args[])
{
try
{
//
throw is used to create a new exception and throw it.
throw
new userdefinedexception(2);
}
catch(userdefinedexception
e)
{
System.out.println(e)
;
}
}
}
Subscribe to:
Posts (Atom)