Maison  >  Article  >  Java  >  Quelle est la différence entre throws et try...catch en Java ?

Quelle est la différence entre throws et try...catch en Java ?

王林
王林avant
2020-02-12 18:07:182164parcourir

Quelle est la différence entre throws et try...catch en Java ?

lance une exception et le code suivant ne sera pas exécuté. Et try...catch lève l'exception et continue d'exécuter le code suivant.

package com.oracle;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo01Exception {
      /*Exception:编译期间异常,进行编译(写代码的过程)
       *  runtimeException:运行期异常,java程序运行过程中出现的问题     
       *Error:错误(出现的错误无法调试,必须修改源代码)
       *  
       */
	public static void main(String[] args){
		//*Exception:编译期间异常,进行编译(写代码的过程)
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化日期对象。
		Date date =null;
		try {
			date = sdf.parse("1999-0909");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//把字符串格式的日期,解析为Date格式日期
		System.out.println(date);
		System.out.println("kkkkk");
	}
}

Résultats de l'exécution : (Apprentissage recommandé : Tutoriel vidéo Java)

java.text.ParseException: Unparseable date: "1999-0909"(无法解释的错误。)
	at java.text.DateFormat.parse(DateFormat.java:357)
	at com.oracle.Demo01Exception.main(Demo01Exception.java:18)
null
kkkkk
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Demo01Exception {
      /*Exception:编译期间异常,进行编译(写代码的过程)
       *  runtimeException:运行期异常,java程序运行过程中出现的问题     
       *Error:错误(出现的错误无法调试,必须修改源代码)
       *  
       */
	public static void main(String[] args) throws ParseException{
		//*Exception:编译期间异常,进行编译(写代码的过程)
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//格式化日期对象。
		Date date =null;
		date = sdf.parse("1999-0909");
		//把字符串格式的日期,解析为Date格式日期
		System.out.println(date);
		System.out.println("kkkkk");
	}
}
Exception in thread "main" java.text.ParseException: Unparseable date: "1999-0909"
	at java.text.DateFormat.parse(DateFormat.java:357)
	at com.oracle.Demo01Exception.main(Demo01Exception.java:17)

Recommandations de didacticiel associées : Tutoriel d'introduction Java

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer
Article précédent:Comment fonctionne HashMap ?Article suivant:Comment fonctionne HashMap ?