0% found this document useful (0 votes)
31 views

Class Lecture On Exceptions in Java

The document describes how to handle exceptions in Java code. It shows an example of a program that takes user input without exception handling that could crash if non-numeric input is entered. It then shows how wrapping the input in a try-catch block allows the program to catch a potential InputMismatchException, handle it by printing a message, and continue executing the rest of the code without crashing. The try-catch construct allows code to gracefully handle exceptions instead of crashing when errors occur.

Uploaded by

Jillian Morgan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Class Lecture On Exceptions in Java

The document describes how to handle exceptions in Java code. It shows an example of a program that takes user input without exception handling that could crash if non-numeric input is entered. It then shows how wrapping the input in a try-catch block allows the program to catch a potential InputMismatchException, handle it by printing a message, and continue executing the rest of the code without crashing. The try-catch construct allows code to gracefully handle exceptions instead of crashing when errors occur.

Uploaded by

Jillian Morgan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Exceptions

Wednesday, April 3, 2019

CSCI 1302 Page 1


1 import java.util.Scanner;
2
3 public class BadCode{
4 public static void main(String[] args){
5 Scanner in = new Scanner(System.in);
6 System.out.print("Enter a number: ");
7
8 int num = in.nextInt();
9
10 System.out.println("You entered " + num);
11
12 System.out.println("done");
13 }
14 }

1 import java.util.Scanner;
2 import java.util.InputMismatchException;
3
4 public class BadCodeALittleBetter{
5 public static void main(String[] args){
6 Scanner in = new Scanner(System.in);

CSCI 1302 Page 2


6 Scanner in = new Scanner(System.in);
7 System.out.print("Enter a number: ");
8
9 try{
10 int num = in.nextInt();
11 System.out.println("You entered " + num);
12 System.out.println("print more stuff");
13 System.out.println("print more stuff");
14 System.out.println("print more stuff");
15 }
16 catch(InputMismatchException ex){
17 System.out.println("That's not a number.");
18 }
19
20 System.out.println("done");
21 System.out.println("print more stuff");
22 System.out.println("print more stuff");
23 System.out.println("print more stuff");
24
25 }
26 }

CSCI 1302 Page 3


CSCI 1302 Page 4

You might also like