欢迎来到天天文库
浏览记录
ID:35342351
大小:62.74 KB
页数:7页
时间:2019-03-23
《实验四--异常处理与多线程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、实验四异常处理与多线程一、实验目的及要求目的:了解异常的概念,掌握异常处理的方法,掌握throws与throw关键字的区别与联系,掌握口定义异常的方法及用途。理解线程的概念,掌握Java的多线程机制,会用多线程编写Java程序。要求:(1)编写程序了解稈序中可能出现的运行时异常与非运行时异常(2)编写程序使用try-catch-finally处理异常,写程序掌握throws与throw的用法(3)理解线程的概念,会用Thread类、Runnable接口创建多线程,对两种实现多线程方式的方式进行对比二、实验环境计算机一台,JDK,
2、EditPlus三、实验原理异常处理方法,Java语言中多线程处理的原理四、实验内容与步骤(一)异常处理1.try-catch-finally处理异常过程importjava.io.*;publicclassEchoInput{publicstaticvoidmaiw(String[]args){System,out.printIn(Entertexttoecho");InputStreainReaderisr=newInputStreamReader(System,in):BufferedReaderinputReader=n
3、ewBufferedReader(isr);try{StringinputLine=inputReader.readLine();System.out.printIn(,vREAD:,v+inputLine):}catch(IOExceptionexc){System,out.printIn("Exceptionencountered:M+exc);}finally!System,out.printingMyjobhereisdone.,v):importjava.io.*;publicclassException4{publi
4、cstaticvoidsnaiziCStringargs[])throwsFileNotFoundException^IOException{FileinputStreamfis=newFileinputStreamCtext.txt'):intb;while((b=fis.read())!=-l){System,out.print(b);}fis.close():}}3.捕获异常(在Exceptionl的基础上加上捕获异常,观察程序运行结果)importjava.io.*;publicclassException5{publi
5、cstaticvoidmain(Stringargs[]){try{FileinputStreamfis=newFileinputStream('text.txt,Y):intb;while((b=fis.read())!=-l){System.out.print(b):}}catch(Fi1eNotFoundExceptione){System.out.println(e);System.out.printIn(message:1+e.getMessage()):e.printStackTrace(System.out);}c
6、atch(IOExceptione){System.out.printIn(e);4.自定义异常调用classMyotherExceptionextendsException{//用户定义的异常publicMyotherException(){publicMyotherException(Stringmsg){super(msg);publicclassExceptions7、ExceptionfromF()f,);thrownewMyotherExceptionO;}publicstaticuoidg()throwsMyotherException{System.out.printInfThrowingMyotherExceptionFromg(),B);thrownewMyotherException(iBOriginateding()iB);}publicstaticuoidnain(String[]args){try{F();}catch(MyotherExceptione){e.prints8、tackTrace();>try{g();}catch(MyotherExceptione){e.printstackTrace();(二)多线程处理1.继承Thread类实现多线程,试着修改setName方法的位置,看看运行效果//MyThread,java^
7、ExceptionfromF()f,);thrownewMyotherExceptionO;}publicstaticuoidg()throwsMyotherException{System.out.printInfThrowingMyotherExceptionFromg(),B);thrownewMyotherException(iBOriginateding()iB);}publicstaticuoidnain(String[]args){try{F();}catch(MyotherExceptione){e.prints
8、tackTrace();>try{g();}catch(MyotherExceptione){e.printstackTrace();(二)多线程处理1.继承Thread类实现多线程,试着修改setName方法的位置,看看运行效果//MyThread,java^
此文档下载收益归作者所有