1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
/*
模拟注册
*/
public
class
Test{
public
static
void
main(String[] args){
//假如用户提供的用户名如下
String username =
"xpleaf"
;
//注册
CustomerService cs =
new
CustomerService();
try
{
cs.register(username);
}
catch
(IllegalNameException e){
System.out.println(e.getMessage());
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//顾客相关的业务
public
class
CustomerService{
//对外提供一个注册的方法
public
void
register(String name)
throws
IllegalNameException{
//完成注册
if
(name.length()<
6
){
//异常
//创建异常对象
//IllegalNameException e = new IllegalNameException("用户名长度不能少6位");
//手动抛出异常
//throw e;
throw
new
IllegalNameException(
"用户名长度不能少6位"
);
}
//如果代码能执行到此处,证明用户名是合法的.
System.out.println(
"注册成功!"
);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/*
自定义“无效名字异常”.
1.编译时异常,直接继承Exception
2.运行时异常,直接继承RuntimeException
*/
public
class
IllegalNameException
extends
Exception{
//编译时异常
//public class IllegalNameException extends RuntimeException{ //运行时异常
//定义异常一般提供两个构造方法
public
IllegalNameException(){}
public
IllegalNameException(String msg){
super
(msg);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import
java.util.Scanner;
public
class
Main_pro {
public
static
void
main(String[] args) {
// TODO Auto-generated method stub
System.out.println(
"Please input a number for a:"
);
Scanner s =
new
Scanner(System.in);
int
a = s.nextInt();
Num_check check =
new
Num_check();
try
{
check.checknum(a);
}
catch
(NumError e){
System.out.println(e.getMessage());
}
}
}
|
1
2
3
4
5
6
7
8
9
|
public
class
Num_check {
public
void
checknum(
int
num)
throws
NumError{
if
(num>=
100
){
throw
new
NumError(
"Error!"
);
}
System.out.println(
"The number is normal."
);
}
}
|
1
2
3
4
5
6
7
|
public
class
NumError
extends
Exception{
public
NumError(){}
public
NumError(String msg){
super
(msg);
}
}
|