0
点赞
收藏
分享

微信扫一扫

Java编译时异常和运行时异常

Java编译时异常和运行时异常_运行时异常

package com.xiaohai;

import java.math.BigInteger;
import java.security.spec.ECPoint;
import java.text.SimpleDateFormat;
import java.util.*;


public class HelloWorld {

public static void main(String[] args) {

HelloWorld h=new HelloWorld();
h.method();
}
//运行时异常
public void method()
{
try {
int[] arr = new int[]{1, 2, 4};
for (int i = 0; i < 4; i++) {
System.out.println(arr[i]);
}
}catch (Throwable e)
{
e.printStackTrace();
System.out.println(e.getMessage());
System.out.println(e.toString());
}
}
//编译时异常
public void method2()
{
String str=new String("2022-2-7");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=sdf.parse(str);
System.out.println(d);
}
}

Java编译时异常和运行时异常_java_02
解决:
方法一

//编译时异常
public void method2()
{
try {
String str=new String("2022-2-7");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=sdf.parse(str);
System.out.println(d);
}
catch (Throwable e)
{

}
}

方法二:

package com.xiaohai;

import java.math.BigInteger;
import java.security.spec.ECPoint;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


public class HelloWorld {

public static void main(String[] args) {

HelloWorld h=new HelloWorld();
try {
h.method2();
} catch (ParseException e) {
e.printStackTrace();
}
}
//编译时异常
public void method2() throws ParseException {
String str=new String("2022-2-7");
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=sdf.parse(str);
System.out.println(d);
}
}


举报

相关推荐

0 条评论