UNC-Chapel Hill COMP 114 - Exceptions (23 pages)

Previewing pages 1, 2, 22, 23 of 23 page document View the full content.
View Full Document

Exceptions



Previewing pages 1, 2, 22, 23 of actual document.

View the full content.
View Full Document
View Full Document

Exceptions

18 views

Problems/Exams


Pages:
23
School:
University of North Carolina at Chapel Hill
Course:
Comp 114 - Foundations of programming

Unformatted text preview:

Exceptions COMP 401 Prasun Dewan1 19 Exceptions So far we have been fairly lax about error handling in that we have either ignored errors or used a simpleminded approach of terminating the program on encountering the first error Moreover error handling code was mixed with regular programming code Furthermore error messages to the user which belong to the user interface were mixed with computation code We will see how these problems can be overcome by using exceptions User Arguments Exception Handling Consider the following program which prints the first argument provided by the user package main public class AnArgPrinter public static void main String args System out println args 0 Figure 1 Printing a User Argument A problem with this program is that the user may have forgotten to supply an argument when executing the program Thus the value 0 provided as the index to args may be out of bounds Of course this is not what the program expects so it does perform correctly if the expected argument is supplied So what will happen if the unexpected case happens Some compilers including Java will automatically put code in the program to check if array subscripts are out of bounds and will terminate the program mentioning that the problem was a subscripting error Other less friendly but more efficient compilers do not bother to do so The program will compute an appropriate memory address where the element is expected and print whatever value is at that memory location If the memory address is outside the range of memory allocated to the program then it will dump core giving no hint of the problem 1 Copyright Prasun Dewan 2009 1 Exceptions None of these solutions are friendly to the users if the program who either get garbage printed out or are told about an subscripting error whose cause they probably cannot correlate with the actual error they committed or are given a core dump message Thus it is important for the programmer to detect the error and react appropriately to it



View Full Document

Access the best Study Guides, Lecture Notes and Practice Exams

Loading Unlocking...
Login

Join to view Exceptions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Exceptions and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?