Debugging Code and Analyzing Logic Errors PDF
Document Details
Uploaded by EnrapturedGyrolite7355
NU Dasmariñas
Tags
Summary
These are lecture notes on debugging code and analyzing logic errors in programming, specifically in Java. The document covers different types of errors, such as syntax errors, runtime errors, and logic errors, and how to identify and handle them.
Full Transcript
Week 4 – 5 Debugging Code and Analyzing Logic Errors CCPRGG2L – Intermediate Programming LEARNING OBJECTIVES At the end of lesson students should be able to: o Recognize errors in program o Create a program that can handle errors and exceptions Programming Errors Programming err...
Week 4 – 5 Debugging Code and Analyzing Logic Errors CCPRGG2L – Intermediate Programming LEARNING OBJECTIVES At the end of lesson students should be able to: o Recognize errors in program o Create a program that can handle errors and exceptions Programming Errors Programming errors are unavoidable, even for experienced programmers. Errors can be categorized into three types: syntax errors, runtime errors, and logic errors. Programming Errors Syntax Errors Errors that occur during compilation are called syntax errors or compile errors. Syntax errors result from errors in code construction, such as mistyping a keyword, omitting some necessary punctuation, or using an opening brace without a corresponding closing brace. These errors are usually easy to detect, because the compiler tells you where they are and what caused them. Programming Errors Syntax Errors Programming Errors Runtime errors These are errors that cause a program to terminate abnormally. They occur while a program is running if the environment detects an operation that is impossible to carry out. Input errors typically cause runtime errors. Programming Errors Runtime errors An input error occurs when the user enters an unexpected input value that the program cannot handle. For instance, if the program expects to read in a number, but instead the user enters a string, this causes data-type errors to occur in the program. To prevent input errors, the program should prompt the user to enter values of the correct type. It may display a message such as “Please enter an integer” before reading an integer from the keyboard. Programming Errors Logic errors This occur when a program does not perform the way it was intended to. Errors of this kind occur for many different reasons. For example, suppose you wrote the following pro- gram to add number1 to number2. Programming Errors Logic errors Debugging In general, syntax errors are easy to find and easy to correct, because the compiler gives indications as to where the errors came from and why they are wrong. Runtime errors are not difficult to find, either, since the reasons and locations of the errors are displayed on the console when the program aborts. Finding logic errors, on the other hand, can be very challenging. Debugging Logic errors are called bugs. The process of finding and correcting errors is called debugging. A common approach is to use a combination of methods to narrow down to the part of the program where the bug is located. Debugging You can hand-trace the program (i.e., catch errors by reading the program), or you can insert print statements in order to show the values of the variables or the execution flow of the program. This approach might work for a short, simple program. But for a large, complex program, the most effective approach is to use a debugger utility. Java Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled. Java Exceptions In Java, exceptions are problems that occur during the execution of a program, disrupting its normal flow. These are represented by objects of the Exception class (or its subclasses) and can be handled using try, catch, and finally blocks. Why Exception Occurs? An exception can occur for many different reasons. Following are some scenarios where an exception occurs. A user has entered an invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. Java Exception Categories 1. Java Errors These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation. Java Exception Categories Print Statement Debugging Print statement debugging in Java involves inserting System.out.println() statements at various points in your code to inspect the values of variables, program flow, or to identify where an issue occurs. Although this approach is simple and effective for small projects, it can become cumbersome in larger applications. Sample program in Netbeans – AverageCalculator class Java Exception Categories 2. Java Checked Exceptions A checked exception is an exception that is checked (notified) by the compiler at compilation-time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of (handle) these exceptions. Java Exception Categories 2. Java Checked Exceptions Checked exceptions are exceptions that are not subclasses of RuntimeException. They must either be caught in a try- catch block or declared in the throws clause of the method where they might occur. A common example of a checked exception is IOException, which occurs during input-output operations like reading from a file or writing to a file. Java Exception Categories 2. Java Checked Exceptions Example: File Reading with IOException In this example, the program attempts to read from a file that may not exist, triggering an IOException. Since IOException is a checked exception, the method must either handle it with a try-catch block or declare it in the throws clause. Java Exception Categories The throw keyword The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundExceptio n, ArrayIndexOutOfBoundsException, SecurityExc eption, etc: The throw keyword Java Exception Categories 3. Java Unchecked Exceptions An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. Java Exception Categories 3. Java Unchecked Exceptions Unchecked exceptions are exceptions that are subclasses of RuntimeException. These exceptions are not required to be explicitly handled using try-catch blocks or declared in the throws clause. Examples include ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, and IllegalArgumentException. Java Exception Categories The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The try and catch keywords come in pairs: Java Exception Categories Example: Java Exception Categories The ArithmeticExcepti on is a built-in exception in Java that occurs when an illegal arithmetic operation is attempted during runtime. It is a subclass of RuntimeException, which means it is an unchecked exception and does not need to be declared in a method's throws clause. Java Exception Categories The finally statement lets you execute code, after try...catch, regardless of the result. Multiple Catch Blocks A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following − Multiple Catch Blocks A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following − Evaluating Stack Trace A stack trace, also called a stack backtrace or even just a backtrace, is a list of stack frames. These frames represent a moment during an application’s execution. A stack frame is information about a method or function that your code called. So the Java stack trace is a list of frames that starts at the current method and extends to when the program started. Evaluating Stack Trace A stack trace in Java is a report generated when an exception is thrown. It provides information about the sequence of method calls that led to the exception. A stack trace is invaluable for debugging, as it allows developers to see exactly where the error occurred and the sequence of method calls that led to it. Evaluating Stack Trace Evaluating Stack Trace When an exception occurs in Java, the JVM (Java Virtual Machine) generates a stack trace. This trace contains details such as: 1. The exception type (e.g., NullPointerException, IOException). 2. A message related to the exception (e.g., Division by zero, File not found). 3. The stack frames (method calls), showing the sequence of method invocations that led to the exception, including: The class name where the exception occurred. The method name. The line number where the exception was thrown. Evaluating Stack Trace Handling Exceptions Using Stack Trace In practice, you can capture a stack trace using the printStackTrace() method. A stack trace is a vital tool in debugging. It tells you where an error occurred and the sequence of method calls that led up to it. By carefully analyzing the stack trace, you can identify the cause of the exception and fix the issue in your code. Evaluating Stack Trace Handling Exceptions Using Stack Trace