异常处理 - 课后作业

1 .阅读并运行下面程序,然后了解Java中实现异常处理的基础知识

import javax.swing.*;

class AboutException {
public static void main(String[] a)
{
int i=1, j=0, k;
//k=i/j;

try
{
k = i/j; // Causes division-by-zero exception
//throw new Exception("Hello.Exception!");
}
catch ( ArithmeticException e)
{
System.out.println("被0除. "+ e.getMessage());
}
catch (Exception e)
{
if (e instanceof ArithmeticException)
System.out.println("被0除");
else
{
System.out.println(e.getMessage());
}
}

finally
{
JOptionPane.showConfirmDialog(null,"OK");
}
}
}

 运行截图:

使用Java异常处理机制:

把可能会发生错误的代码放进try语句块中。

当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误。

catch语句块中的代码用于处理错误。

当异常发生时,程序控制流程由try语句块跳转到catch语句块。

不管是否有异常发生,finally语句块中的语句始终保证被执行。

如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。

 

2 .请尝试解释以下奇怪的现象:

用javap去反汇编两个示例程序的.class文件。第一个程序生成idiv字节码指令,第二个程序生成ddiv字节码指令。

JVM在具体实现这两个指令时,采用了不同的处理策略,导致两段代码运行时得到不同的结果

 3 .阅读以下代码,写出程序运行结果:

public class CatchWho { 
    public static void main(String[] args) { 
        try { 
            	try { 
                	throw new ArrayIndexOutOfBoundsException(); 
            	} 
            	catch(ArrayIndexOutOfBoundsException e) { 
               		System.out.println(  "ArrayIndexOutOfBoundsException" +  "/内层try-catch"); 
            	}
 
            throw new ArithmeticException(); 
        } 
        catch(ArithmeticException e) { 
            System.out.println("发生ArithmeticException"); 
        } 
        catch(ArrayIndexOutOfBoundsException e) { 
           System.out.println(  "ArrayIndexOutOfBoundsException" + "/外层try-catch"); 
        } 
    } 
}

运行截图:

4 .写出程序运行的结果:

public class CatchWho2 { 
    public static void main(String[] args) { 
        try {
            	try { 
                	throw new ArrayIndexOutOfBoundsException(); 
            	} 
            	catch(ArithmeticException e) { 
                	System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); 
            	}
            throw new ArithmeticException(); 
        } 
        catch(ArithmeticException e) { 
            System.out.println("发生ArithmeticException"); 
        } 
        catch(ArrayIndexOutOfBoundsException e) { 
            System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); 
        } 
    } 
}

 运行截图:

5 .阅读示例,再运行它,观察其输出并进行总结。

public class EmbededFinally {
	public static void main(String args[]) {
		int result;
		try {
			System.out.println("in Level 1");
		 	try {
				System.out.println("in Level 2");
  // result=100/0;  //Level 2               
 				try {
				 	System.out.println("in Level 3");
				 	result=100/0;  //Level 3
				} 
				catch (Exception e) {
                    
					System.out.println("Level 3:" + e.getClass().toString());
				}
                                
				finally {
                    
					System.out.println("In Level 3 finally");
                
				}                               
				// result=100/0;  //Level 2            
				}            
			catch (Exception e) {              
			 	System.out.println("Level 2:" + e.getClass().toString());
		 	}
		 	finally {
                
				System.out.println("In Level 2 finally");
			 }
             
			// result = 100 / 0;  //level 1
		} 
		catch (Exception e) {
			System.out.println("Level 1:" + e.getClass().toString());
		}
		finally {
		 	System.out.println("In Level 1 finally");      
		}    
	}
}

  运行截图:

总结:

try...catch语句为配对出现,程序会按着代码的顺序依次执行,当try中语句出现异常时,他会执行与当前try配对的catch语句。

 

 6 .finally语句块一定会执行吗?请通过 示例程序回答问题

程序:

public class SystemExitAndFinally {
    
	public static void main(String[] args)
    {
       
		try{
            
			System.out.println("in main");
            
			throw new Exception("Exception is thrown in main");

            		//System.exit(0);
        
		}
        
		catch(Exception e)
	        {            
			System.out.println(e.getMessage());
            
			System.exit(0);     
		}
        
		finally
		{            
			System.out.println("in finally");        
		}    
	}
}

  运行结果:

finally不会每次都执行,例如以上程序,当执行完throw new Exception("Exception is thrown in main");语句后便关闭了程序。

 7 . 如何跟踪异常的传播路径?

当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。

可使用printStackTrace 和 getMessage方法了解异常发生的情况:

        printStackTrace:打印方法调用堆栈。

        每个Throwable类的对象都有一个getMessage方法,它返回一个字串,这个字串是在Exception构造函数中传入的,通常让这一字串包含特定异常的相关信息。

 示例程序:

//UsingExceptions.java
//Demonstrating the getMessage and printStackTrace
//methods inherited into all exception classes.
public class PrintExceptionStack {
public static void main( String args[] )
{
   try {
      method1();
   }
   catch ( Exception e ) {
      System.err.println( e.getMessage() + "\n" );
      e.printStackTrace();
   }
}

public static void method1() throws Exception
{
   method2();
}

public static void method2() throws Exception
{
   method3();
}

public static void method3() throws Exception
{
   throw new Exception( "Exception thrown in method3" );
}
}

  截图:

 

8 .以下代码完全符合Java语法规范,但是为什么它们不能通过编译:

public class TestThrows   {
		public static void main(String[] args)     {
			FileInputStream fis = new                       
                                                   FileInputStream("a.txt");
			}
	}

  throws语句表明某方法中可能出现某种(或多种)异常,但它自己不能处理这些异常,而需要由调用者来处理。 当一个方法包含throws子句时,需要在调用此方法的代码中使用try/catch/finally进行捕获,或者是重新对其进行声明,否则编译时报错。

 

9 .编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。

import java.util.Scanner;

public class Test 
{   
	public static void main(String[] args) 
	{  
		try 
		{
            System.out.println("请输入成绩");
            Scanner in=new Scanner(System.in);
            double a=in.nextDouble();
            
            if(a<60&&a>=0) System.out.println("不及格");
             
            else if(a<70) System.out.println("及格");
                    
            else if(a<80) System.out.println("中");
                        
            else if(a<90) System.out.println("良");
                            
            else if(a>=90&&a<=100) System.out.println("优");
                               
            else  System.out.println("成绩无效");
        }
		
        catch(Exception e) 
		{
            System.out.println("成绩无效");
        }
    }

}

  

 

转载于:https://www.cnblogs.com/liboxun/p/7846858.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
java3think in java笔记(111)---打印 (2008-04-24 16:58:28) 标签:杂谈 1 默认情况下,print()方法会调用paint()来完成自己的工作。 2 选择一种字体和大小,决定字符串在页面上存在的位置,并且使用Graphics.drawSrting()方法在页面上画出字符串.必须精确地计算每行字符串在页面上存在的位置并确定字符串不会超出页面底部或者同其它行冲突。 import java.awt.*; import java.awt.event.*; public class PrintDemo extends Frame { Button printText = new Button("Print Text"), printGraphics = new Button("Print Graphics"); TextField ringNum = new TextField(3); Choice faces = new Choice(); Graphics g = null; Plot plot = new Plot3(); // Try different plots Toolkit tk = Toolkit.getDefaultToolkit(); public PrintDemo() { ringNum.setText("3"); ringNum.addTextListener(new RingL()); Panel p = new Panel(); p.setLayout(new FlowLayout()); printText.addActionListener(new TBL()); p.add(printText); p.add(new Label("Font:")); p.add(faces); printGraphics.addActionListener(new GBL()); p.add(printGraphics); p.add(new Label("Rings:")); p.add(ringNum); setLayout(new BorderLayout()); add(p, BorderLayout.NORTH); add(plot, BorderLayout.CENTER); String[] fontList = tk.getFontList(); for(int i = 0; i < fontList.length; i++) faces.add(fontList[i]); faces.select("Serif"); } class PrintData { public PrintJob pj; public int pageWidth, pageHeight; PrintData(String jobName) { pj = getToolkit().getPrintJob( PrintDemo.this, jobName, null); if(pj != null) { pageWidth = pj.getPageDimension().width; pageHeight= pj.getPageDimension().height; g = pj.getGraphics(); } } void end() { pj.end(); } } class ChangeFont { private int stringHeight; ChangeFont(String face, int style,int point){ if(g != null) { g.setFont(new Font(face, style, point)); stringHeight = g.getFontMetrics().getHeight(); } } int stringWidth(String s) { return g.getFontMetrics().stringWidth(s); } int stringHeight() { return stringHeight; } } class TBL implements ActionListener { public void actionPerformed(ActionEvent e) { PrintData pd = new PrintData("Print Text Test"); // Null means print job canceled: if(pd == null) return; String s = "PrintDemo"; ChangeFont cf = new ChangeFont( faces.getSelectedItem(), Font.ITALIC,72); g.drawString(s, (pd.pageWidth - cf.stringWidth(s)) / 2, (pd.pageHeight - cf.stringHeight()) / 3); s = "A smaller point size"; cf = new ChangeFont( faces.getSelectedItem(), Font.BOLD, 48); g.drawString(s, (pd.pageWidth - cf.stringWidth(s)) / 2, (int)((pd.pageHeight - cf.stringHeight())/1.5)); g.dispose(); pd.end(); } } class GBL implements ActionListener { public void actionPerformed(ActionEvent e) { PrintData pd = new PrintData("Print Graphics Test"); if(pd == null) return; plot.print(g); g.dispose(); pd.end(); } } class RingL implements TextListener { public void textValueChanged(TextEvent e) { int i = 1; try { i = Integer.parseInt(ringNum.getText()); } catch(NumberFormatException ex) { i = 1; } plot.rings = i; plot.repaint(); } } public static void main(String[] args) { Frame pdemo = new PrintDemo(); pdemo.setTitle("Print Demo"); pdemo.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); pdemo.setSize(500, 500); pdemo.setVisible(true); } } class Plot extends Canvas { public int rings = 3; } class Plot1 extends Plot { // Default print() calls paint(): public void paint(Graphics g) { int w = getSize().width; int h = getSize().height; int xc = w / 2; int yc = w / 2; int x = 0, y = 0; for(int i = 0; i < rings; i++) { if(x < xc && y < yc) { g.drawOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; } } } } class Plot2 extends Plot { // To fit the picture to the page, you must // know whether you're printing or painting: public void paint(Graphics g) { int w, h; if(g instanceof PrintGraphics) { PrintJob pj = ((PrintGraphics)g).getPrintJob(); w = pj.getPageDimension().width; h = pj.getPageDimension().height; } else { w = getSize().width; h = getSize().height; } int xc = w / 2; int yc = w / 2; int x = 0, y = 0; for(int i = 0; i < rings; i++) { if(x < xc && y < yc) { g.drawOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; } } } } class Plot3 extends Plot { // Somewhat better. Separate // printing from painting: public void print(Graphics g) { // Assume it's a PrintGraphics object: PrintJob pj = ((PrintGraphics)g).getPrintJob(); int w = pj.getPageDimension().width; int h = pj.getPageDimension().height; doGraphics(g, w, h); } public void paint(Graphics g) { int w = getSize().width; int h = getSize().height; doGraphics(g, w, h); } private void doGraphics( Graphics g, int w, int h) { int xc = w / 2; int yc = w / 2; int x = 0, y = 0; for(int i = 0; i < rings; i++) { if(x < xc && y < yc) { g.drawOval(x, y, w, h); x += 10; y += 10; w -= 20; h -= 20; } } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值