exceptions - Exceptions Exceptions When writing programs,...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Exceptions Exceptions When writing programs, it’s good to think about all the situations where things could go wrong. For example, if you ask the user to input an integer, you should probably check to see if they actually did. Java has a special class called Exception that is used when things go wrong in a program. If you reach a certain error state (such as getting bad input), you can throw an exception that describes the error. You can also try troublesome code, and then catch (and handle) any problems that might have happened. Try/Catch Block Here’s the format for trying code that might cause problems, and then catching and handling the errors: try { code that might cause problems } catch (Exception e) { handle the error } Suppose I try to read from a file that doesn’t exist. That could certainly cause problems! To handle this, I’m going to try reading from a file, and will catch any problems: Scanner console = new Scanner(System.in); try { System.out.print(“Input the name of a file: “); String name = console.nextLine(); Scanner fileIn = new Scanner(new File(name)); String line = fileIn.nextLine(); System.out.println(“1 st line: “ + line); } catch (Exception e) { System.out.println(“Error reading file.”);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 03/02/2010 for the course CIS 200 taught by Professor Staff during the Spring '08 term at Kansas State University.

Page1 / 4

exceptions - Exceptions Exceptions When writing programs,...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online