package com.base.exception;
public class Car {
String name;
public Car() {
// TODO Auto-generated constructor stub
this.name = "";
}
public Car(String name) {
// TODO Auto-generated constructor stub
this.name = name;
}
public String toString() {
return "Car [name=" + name + "]";
}
}
package com.base.exception;
public class MessageData {
private T data;
private String message;
private int code;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "MessageData [data=" + data + ", message=" + message + ", code=" + code + "]";
}
}
package com.base.exception;
public class SomeExceptions {
//字符串转整形——类型转换异常
public static int stringToInt(String str) throws Exception{
int tt = 0;
try{
tt = Integer.parseInt(str);
}catch(Exception e){
throw new Exception("stringToInt的参数:"+str+" 格式错误导致异常发生!");
}
return tt;
}
//查找数组中第10个数——数组越界异常
public static int selectNumFormArray(int[] a) throws Exception{
try{
return a[10];
}catch(Exception e){
throw new Exception("selectNumFormArray的参数:"+a+"导致异常发生!");
}
}
//去除字符串首尾空格——空指针异常
public static String deleteSpace(String str) throws Exception{
try{
return str.trim();
}catch(Exception e){
throw new Exception("deleteSpace的参数:"+str+"导致异常发生!");
}
}
//除法运算——除数为零异常
public static int invide(int a,int b) throws Exception{
try{
return a/b;
}catch(Exception e){
throw new Exception("invide的参数:"+b+"导致异常发生!");
}
}
//打印年龄——代码逻辑异常
public static void sayYourAge(int age) throws Exception{
if((age < 0) || (age > 100)){
throw new Exception("年龄小于0或者大于100了!");
}
System.out.println("你的年龄是"+age);
}
}
package com.base.exception;
public interface MethodsInterface {
MessageData tellStation();
}
package com.base.exception;
public class UseMethods implements MethodsInterface {
public MessageData tellStation() {
// TODO Auto-generated method stub
//创建返回数据对象
MessageData md = new MessageData<>();
try{
//空指针异常
SomeExceptions.deleteSpace(" ");
//除数为零异常
SomeExceptions.invide(10, 1);
//代码逻辑异常
SomeExceptions.sayYourAge(-100);
//数组越界异常
int[] a = {1};
SomeExceptions.selectNumFormArray(a);
//类型转换异常
SomeExceptions.stringToInt("fasf");
}catch(Exception e){
//创建汽车对象
Car shifeng = new Car("时风");
//封装返回对象
md.setData(shifeng);
md.setCode(444);
md.setMessage(e.getMessage());
return md;
}
Car baoma = new Car("宝马");
//封装返回对象
md.setData(baoma);
md.setCode(888);
md.setMessage("你成功获得一辆宝马!");
return md;
}
}
package com.base.exception;
public class TestExceptions {
public static void main(String[] args) {
// TODO Auto-generated method stub
MethodsInterface sm = new UseMethods();
//调用异常方法,返回运行状态
MessageData station = sm.tellStation();
//打印数据
System.out.println("返回数据为:"+station.toString());
}
}