Lesson 6 Handling Errors
Lesson 6 Handling Errors
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
Send to Printer | Close Window
Lesson 6: Handling errors
Lesson 6: Handling errors
Lesson 6: Handling errors
Objectives
Objectives
In this lesson, you will learn how to:
Describe the different kinds of errors that can occur and how they are handled in J ava
Describe what exceptions are used for in J ava
Determine what exceptions are thrown for any foundation class
Write code to handle an exception thrown by the method of a foundation class
Purpose
Having errors in your code can be frustrating. Knowing how to handle errors and exceptions will help make your
code work properly.
Imagine using a program that does not work the way it should. Would you continue to use it?
This lesson will teach you how to recognize and handle common errors in J ava and introduce exceptions and exception handling.
Types of errors
Types of errors
Types of Errors
An error indicates that a there is a problem with interpreting your program.
There are three types of errors:
Syntax Errors
Logic Errors
Exceptions (Run-Time Errors)
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
We will look into each one of these types of errors.
Syntax Errors
An error can occur when a file is compiled. These errors are coding or syntax errors, such as missing semi-colons,
spelling errors, trying to assign a value to a variable that is not the correct type, etc. These are usually the easiest errors to correct,
since the J ava compiler or Eclipse will indicate to you that there is an error.
It is common to go through several rounds of fixing syntax errors before compiling the file is successful.
1) Forgetting a semicolon at the end of a java statement is a syntax error.
Example:
Using =instead of ==to compare values in an if condition is a syntax error.
2) Misspelling a variable or method name is a syntax error. Be sure to verify that you have spelled the variable or method the same as
you declared it.
Logic Errors
Logic errors occur as a result of programmer logic that is incorrect. These errors do not produce a compile or runtime
error. For example, a loop runs too many times, or the program produces incorrect output. These errors are usually harder to resolve,
since you need to go through the code line by line to determine whether it is doing what it is suppose to.
Placing a semicolon after an if condition or initializing a loop:
i nt sum= 0;
f or ( i nt i = 0; i < 5; i ++) ;
sum= sum+ i ;
or using ==to compare two String instead of .equal() method.
St r i ng s1, s2;
s1 = " hi " ;
s2 = " hel l o" ; l
i f ( s1==s2)
St r i ng equal = " yes" ;
el se
St r i ng equal = " no" ;
Interpreters read the semicolon as the end of the loop, which means that everything after the semicolon will be treated as outside of
the loop.
Exceptions
Once a file compiles successfully, an error can occur when a file is being tested during run time. These run-time errors
are called exceptions and should be handled by the programmer using code in the program. The correct terminology is that the code
will throw an exception.
For example: The user is requested to enter his/her ID number. Since I am going to use String manipulation, the ID is read as a
String. Because the input is String, the user can enter anything. He can even type in his name or by mistake enter an "O" instead of a
"0" (zero).
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
J ava exceptions fall into two categories:
Unchecked Exceptions
Checked Exceptions, most of which originate in programs with Input/Output (IO).
But, we as programmers can try and catch these errors before it crashes the application. Both checked and unchecked Exceptions can
be handled by creating a try/catch block.
Below is is an example of a try/catch block.
t r y{
. . . code t hat may cause an except i on
}
cat ch ( Except i on e) {
. . . code t o handl e i f t her e i s an except i on
}
Unchecked Exceptions
It is optional to handle unchecked exceptions in J ava.
However, if the unchecked exception is not handled, and an error occurs, the program will crash.
Common unchecked exceptions:
Index out of bounds exception, e.g. the code refers to an index in an array which doesn't exist.
Example:
i nt [ ] myAr r ay = {1, 2, 3};
What woul d happen i f I cal l myAr r ay[ 3] ?
Remember that indexes are counted starting by 0, thus myArray[3] does not exist.
Null pointer exception
This often happens when an object is not inialised.
For Example:
St r i ng s1; / / s1 has no i ni t i al val ue
s1 = s1 + " hi " ;
It often happens in Android Application.
Specifically where you are referring to a field (EditView) but there is at that stage to information in the field.
File Not Found Exception (1)
File Not Found Exception is an IO exception. IO exceptions are checked exceptions. Most checked exceptions come
from using I/O classes.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
Checked exceptions MUST be handled. The programmer can use a try/catch block to handle checked exceptions OR use a throws
statement in the method declaration.
We will still get to this, but here is an example of such code that will prevent the compiler to read information from a file that does not
exist:
t r y{
Fi l eReader r eader = new Fi l eReader ( t est . t xt ) ;
}
cat ch( I OExcept i on e) {
St r i ng er r or Message = " Fi l e not f ound" ;
}
File Not Found Exception (2)
Using a throws statement to handle an IO Exception:
publ i c st at i c voi d mai n( St r i ng[ ] ar gs) t hr ows I OExcept i on{
Fi l eReader r eader = new Fi l eReader ( " t est . t xt " ) ;
Note: The throws statement handles the exception, however, this program will crash if an error occurs that throws an exception
Catching exceptions
Catching exceptions
Catching Exceptions
To catch an exception means to handle it.
You may throw an exception for certain cases, such as going out of bounds of an array and catch the exception to continue the
program the way you wrote it to handle the exception.
Using a try-catch block enables you to do this.
Create a new Android Application and call it ErrorHandling.
- Create one Screen
- Create one EditText, one TextView and one button (for the coding).
- Add the necessary code to link all the widgets to the coding.
First scenario:
The user must enter his/her age in the EditText field.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
Test that the user enters an integer for his/her age. If not, send a message to the user using Toast .
/ / l i nki ng t he wi dget s t o t he code
final EditText fInput = (EditText)findViewById(R.id.edInput);
final TextView fDisplay = (TextView)findViewById(R.id.txtDisplay);
Button btnShow = (Button)findViewById(R.id.btnShow);
bt nShow. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
//This is where your code will go
String sInput = fInput.getText().toString();
try{
int age = Integer.valueOf(sInput);
fDisplay.setText("you are " + sInput + " years old");
}
catch(Exception e)
{
Toast.makeText(MainActivity.this, "Please enter your age",
Toast.LENGTH_SHORT).show();
}
}/ / end of onCl i ck
}) ; / / but t on
Save, compile, correct any syntax errors and run the code.
We haven't really dealt with Toast , but it's purpose is rather obvious. It send a message directly to the user on the screen.
Thus, how would you test if an ID number was entered.
You cannot test for integer, since the value is to large. What I would suggest is to write a small script (method or procedure that will
test each individual element in the String. The script will return true if the ID is valid or false if the ID is not valid.
Below is an example of such code.
@Over r i de
pr ot ect ed voi d onCr eat e( Bundl e savedI nst anceSt at e) {
super . onCr eat e( savedI nst anceSt at e) ;
set Cont ent Vi ew( R. l ayout . act i vi t y_mai n) ;
/ / l i nki ng t he wi dget s t o t he code
fInput = (EditText)findViewById(R.id.edInput);
fDisplay = (TextView)findViewById(R.id.txtDisplay);
But t on bt nShow = ( But t on) f i ndVi ewByI d( R. i d. bt nShow) ;
bt nShow. set OnCl i ckLi st ener ( new OnCl i ckLi st ener ( ) {
publ i c voi d onCl i ck( Vi ew v) {
/ / Thi s i s wher e your code wi l l go
String sId = fInput.getText().toString();
//call the method IdValid(variable to pass). true/false is returned
if (IdValid(sId)){
fDisplay.setText("The id is valid");
}
else fDisplay.setText("The id is invalid");
}//end of onClick
/ / . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
/ / my met hods. . . . .
private boolean IdValid(String sId) {
// TODO Auto-generated method stub
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
boolean isValid = true; //assume the ID is valid and
// will change it to false if there is a problem
int len = sId.length();
for (int i=0; i < len; i++){
try
{
//try to convert the number to int
int numb = Integer.parseInt(sId.substring(i,i+1));
}
catch (Exception e){
//if it can't convert to in, set isValid false
//exit the code and return
isValid = false;
break;
}//try-catch
}//i
return isValid;
}
//.................end of methods ............
});//button
}
Downl oad t he code f r ommyUNI SA i s you st r uggl e.
One hi nt . . .
Should you wish to create a method or procedure in Eclipse, then simply type in the name of the method, in this instance IdValid(sId).
Eclipse will ask you whether you would like to create the method. Say yes. Go down to where it is created and complete the code.
Reflection
Reflection
Reflection
Lesson 6: Summary
Now it is your turn ...
In the blogger add a blog entry. Label it Lesson 6. In this blog, enter a short summary for yourself of everything that we've learned.
Specifically those components that you've battled with and how you solved it.
Modules: Print Module
https://my.unisa.ac.za/portal/tool/83279629-dfa5-4921-8517-4eab4f78908e/print_module.jsf?printModuleId=233144347[05/09/2014 16:41:51]
Remember to keep notes and updates in your little black book.
Click here