public class Test {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
try{
for (int i = 0; i < arr.length + 1; i++) {
System.out.println(arr[i]);
}
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
结果
public class Test {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3,4,5};
try{
for (int i = 0; i < arr.length + 1; i++) {
System.out.println(arr[i]);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
结果
throws + 异常类型
public class StudentTest {
public static void main(String[] args) {
Student s = new Student();
try {
s.regist(-1001);
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
System.out.println(s);
}
}
class Student{
private int id;
public void regist(int id){
if(id > 0){
this.id = id;
}else{
// System.out.println("您输入的值非法!");
//手动抛出异常对象
throw new RuntimeException("您输入的值非法!");
// throw new Exception("您输入的值非法!");
}
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
‘}‘;
}
}
class MyException extends RuntimeException{
static final long serialVersionUID = -7034897190745766939L;
public MyException() {
}
public MyException(String message) {
super(message);
}
}
public class StudentTest {
public static void main(String[] args) {
Student s = new Student();
try {
s.regist(-1001);
} catch (Exception e) {
// e.printStackTrace();
System.out.println(e.getMessage());
}
System.out.println(s);
}
}
class Student{
private int id;
public void regist(int id){
if(id > 0){
this.id = id;
}else{
// System.out.println("您输入的值非法!");
throw new MyException("不能输入负数");
}
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
‘}‘;
}
}
原文:https://www.cnblogs.com/CrabDumplings/p/13190694.html