Apart from existing Exceptions in
java, we can create our own Exceptions (User defined exceptions in java), we
will how to..
Required
files
- Client.java [ My business logic will goes here ]
- MyOwnExceptionClass.java [ This is our own Exception class ]
Note: Our user defined class must extend
from Exception class, and we must override the toString() method to display our
exception message.
Client.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
package java4s;
public class Client {
public static void main(String[]
args)throws Exception
{
int price = -120;
if(price < 0)
throw
new MyOwnExceptionClass(price);
else
System.out.println("Your
age is :"+price);
}
}
|
MyOwnExceptionClass.java
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
package java4s;
public class MyOwnExceptionClass
extends Exception {
private
int price;
public
MyOwnExceptionClass(int price){
this.price
= price;
}
public
String toString(){
return "Price should not be in negative, you are entered"
+price;
}
}
|
No comments:
Post a Comment