(java 基础知识) java异常抛出和返回值

无情 阅读:802 2021-03-31 22:12:19 评论:0
异常处理的流程: 
① 遇到错误,方法立即结束,并不返回一个值;同时,抛出一个异常对象 。
File file = new File("文件存储地址"); 
但“存储文件地址”不存在,会在程序执行中,报文件空指针异常。 

② 调用该方法的程序也不会继续执行下去,而是搜索一个可以处理该异常的异常处理器,并执行其中的代码 。
第一种情况:
public static void main(String[] args) { 
<span style="white-space:pre">		</span>// TODO Auto-generated method stub 
<span style="white-space:pre">		</span>String name = null; 
<span style="white-space:pre">		</span>try{ 
<span style="white-space:pre">			</span>File file =new File("d://ss//sed.txt"); 
<span style="white-space:pre">			</span>name = "知道"; 
<span style="white-space:pre">			</span>FileInputStream input =new FileInputStream(file);<span style="white-space:pre">			</span> 
<span style="white-space:pre">		</span>}catch(Exception e){<span style="white-space:pre">			</span> 
<span style="white-space:pre">			</span>name = "不知道"; 
<span style="white-space:pre">			</span>System.out.println("文件名称是:"+name);<span style="white-space:pre">			</span> 
<span style="white-space:pre">		</span>} 
<span style="white-space:pre">		</span>System.out.println("文件名称是:"+name); 
 
 
<span style="white-space:pre">	</span>}
结果:file 文件为空,FileInputStream 会报错“文件为空”,程序会执行catch 模块的逻辑片段,最后的输出结果为:两个不知道
第二种情况:
	public static void main(String[] args) throws FileNotFoundException { 
		// TODO Auto-generated method stub 
		String name = null; 
		File file =new File("d://ss//sed.txt"); 
		name = "知道"; 
		FileInputStream input =new FileInputStream(file); 
		System.out.println("文件名称是:"+name);
	} 
结果:file文件为空,FileInputStream会提示“文件为空”,程序会执行FileNotException 中的相关逻辑代码,最后不会输出任何结果。
 
第三种情况:
public static void main(String[] args)  { 
		// TODO Auto-generated method stub 
		String name = null; 
		File file =new File("d://ss//sed.txt"); 
		name = "知道"; 
	 
			 
	        try { 
	         
	        	FileInputStream input =new FileInputStream(file); 
	        	throw new Exception(); 
			} catch (Exception e) { 
				// TODO Auto-generated catch block 
				e.printStackTrace(); 
			} 
		System.out.println("文件名称是:"+name); 
 
	}

结果:file文件为空,FileInputStream会提示“文件为空”,程序会执行Exception中的相关逻辑代码,最后输出结果:"知道"。

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号