Sunday, February 27, 2011

Contoh Program Delphi kalkulator sederhana

Baiklah bagi rekan yang baru bergabung dengan dunia pemrograman delphi, berikut akan saya bagikan contoh program delphi yaitu kalkulator sederhana  beserta source codenya silahkan di download gratis kok.

Download Disini

Linux dan Windows

RPL XX

Linux dan Windows

saati ini saya merasa tertari dengan yang namanya networking dan saya berfikir bagaimanakah caranya untuk mengkoneksikan antara sistem operasi winodws dan linux dalam 1 jaringan yang sama dan dengan kabel penghubung yang sama.

saya sama sekali belum tahu bagai mana cara menyambungkan atau mengkoneksikan anatar kedua sistem operasi tersebut namun saya akan mencoba dan mencari informasi serta terus ber eksperimen agar saya bisa tahu dan mampu melakukannya jika suatu saat diperlukan.

selain itu saya juga akan mencoba ini di dalam 1 PC yang sama dengan menggunakan VMW. kira-kira apakah yang akan terjadi nantinya?

kita tunggu saja hingga selesai ber eksperimen, apakah berhasil atau kah tidak sama sekali

Saturday, February 26, 2011

Simple Delphi data types

Simple Delphi data types
Like many modern languages, Delphi provides a rich variety of ways of storing data. We'll cover the basic, simple types here. Before we do, we'll show how to define a variable to Delphi:

var // This starts a section of variables
LineTotal : Integer; // This defines an Integer variable called LineTotal
First,Second : String; // This defines two variables to hold strings of text

We'll show later exactly where this var section fits into your program. Notice that the variable definitions are indented - this makes the code easier to read - indicating that they are part of the var block.

Each variable starts with the name you choose, followed by a : and then the variable type. As with all Delphi statements, a ; terminates the line. As you can see, you can define multiple variables in one line if they are of the same type.

It is very important that the name you choose for each variable is unique, otherwise Delphi will not know how to identify which you are referring to. It must also be different from the Delphi language keywords. You'll know when you have got it right when Delphi compiles your code OK (by hitting Ctrl-F9 to compile).

Delphui is not sensitive about the case (lower or upper) of your names. It treats theCAT name the same as TheCat.

Number types
Delphi provides many different data types for storing numbers. Your choice depends on the data you want to handle. Our Word Processor line count is an unsigned Integer, so we might choose Word which can hold values up to 65,535. Financial or mathematical calculations may require numbers with decimal places - floating point numbers.

var
// Integer data types :
Int1 : Byte; // 0 to 255
Int2 : ShortInt; // -127 to 127
Int3 : Word; // 0 to 65,535
Int4 : SmallInt; // -32,768 to 32,767
Int5 : LongWord; // 0 to 4,294,967,295
Int6 : Cardinal; // 0 to 4,294,967,295
Int7 : LongInt; // -2,147,483,648 to 2,147,483,647
Int8 : Integer; // -2,147,483,648 to 2,147,483,647
Int9 : Int64; // -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

// Decimal data types :
Dec1 : Single; // 7 significant digits, exponent -38 to +38
Dec2 : Currency; // 50+ significant digits, fixed 4 decimal places
Dec3 : Double; // 15 significant digits, exponent -308 to +308
Dec4 : Extended; // 19 significant digits, exponent -4932 to +4932

Some simple numerical variable useage examples are given below - fuller details on numbers is given in the Numbers tutorial.

Text types
Like many other languages, Delphi allows you to store letters, words, and sentences in single variables. These can be used to display, to hold user details and so on. A letter is stored in a single character variable type, such as Char, and words and sentences stored in string types, such as String.

var
Str1 : Char; // Holds a single character, small alphabet
Str2 : WideChar; // Holds a single character, International alphabet
Str3 : AnsiChar; // Holds a single character, small alphabet
Str4 : ShortString; // Holds a string of up to 255 Char's
Str5 : String; // Holds strings of Char's of any size desired
Str6 : AnsiString; // Holds strings of AnsiChar's any size desired
Str7 : WideString; // Holds strings of WideChar's of any size desired

Some simple text variable useage examples are given below - fuller details on strngs and characters is given in the Text tutorial.

Logical data types
These are used in conjunction with programming logic. They are very simple:

var
Log1 : Boolean; // Can be 'True' or 'False'

Boolean variables are a form of enumerated type. This means that they can hold one of a fixed number of values, designated by name. Here, the values can be True or False. See the tutorials on Logic and Looping for further details.

Sets, enumerations and subtypes
Delphi excels in this area. Using sets and enumerations makes your code both easier to use and more reliable. They are used when categories of data are used. For example, you may have an enumeration of playing card suits. You literally enumerate the suit names. Before we can have an enumerated variable, we must define the enumeration values. This is done in a type section.

type
TSuit = (Hearts, Diamonds, Clubs, Spades); // Defines the enumeration
var
suit : TSuit; // An enumeration variable

Sets are often confused with enumerations. The difference is tricky to understand. An enumeration variable can have only one of the enumerated values. A set can have none, 1, some, or all of the set values. Here, the set values are not named - they are simply indexed slots in a numeric range. Confused? Well, here is an example to try to help you out. It will introduce a bit of code a bit early, but it is important to understand.

type
TWeek = Set of 1..7; // Set comprising the days of the week, by number
var
week : TWeek;
begin
week := [1,2,3,4,5]; // Switch on the first 5 days of the week
end;

See the Set reference, and the Sets and enumerations tutorial for further details. That tutorial introduces a further data type - a subrange type.


Using these simple data types
Variables can be read from and written to. This is called assignment. They can also be used in expressions and programming logic. See the Text tutorial and Programming logic tutorial for more about these topics.

Assigning to and from variables
Variables can be assigned from constant values, such as 23 and 'My Name', and also from other variables. The code below illustrates this assignment, and also introduces a further section of a Delphi program : the const (constants) section. This allows the programmer to give names to constant values. This is useful where the same constant is used throughout a program - a change where the constant is defined can have a global effect on the program.

Note that we use upper case letters to identify constants. This is just a convention, since Delphi is not case sensitive with names (it is with strings). Note also that we use = to define a constant value.

types
TWeek = 1..7; // Set comprising the days of the week, by number
TSuit = (Hearts, Diamonds, Clubs, Spades); // Defines an enumeration

const
FRED = 'Fred'; // String constant
YOUNG_AGE = 23; // Integer constant
TALL : Single = 196.9; // Decimal constant
NO = False; // Boolean constant

var
FirstName, SecondName : String; // String variables
Age : Byte; // Integer variable
Height : Single; // Decimal variable
IsTall : Boolean; // Boolean variable
OtherName : String; // String variable
Week : TWeek; // A set variable
Suit : TSuit; // An enumeration variable

begin // Begin starts a block of code statements
FirstName := FRED; // Assign from predefined constant
SecondName := 'Bloggs'; // Assign from a literal constant
Age := YOUNG_AGE; // Assign from predefined constant
Age := 55; // Assign from constant - overrides YOUNG_AGE
Height := TALL - 5.5; // Assign from a mix of constants
IsTall := NO; // Assign from predefined constant
OtherName := FirstName; // Assign from another variable
Week := [1,2,3,4,5]; // Switch on the first 5 days of the week
Suit := Diamonds; // Assign to an enumerated variable
end; // End finishes a block of code statements

FirstName is now set to 'Fred'
SecondName is now set to 'Bloggs'
Age is now set to 55
Height is now set to 191.4
IsTall is now set to False
OtherName is now set to 'Fred'
Week is now set to 1,2,3,4,5
Suit is now set to Diamonds (Notice no quotes)

Note that the third constant, TALL, is defined as a Single type. This is called a typed constant. It allows you to force Delphi to use a type for the constant that suits your need. Ohterwise, it will make the decision itself.


Compound data types
The simple data types are like single elements. Delphi provides compound data types, comprising collections of simple data types.

These allow programmers to group together variables, and treat this group as a single variable. When we discuss programming logic, you will see how useful this can be.

Arrays
Array collections are accessed by index. An array holds data in indexed 'slots'. Each slot holds one variable of data. You can visualise them as lists. For example:

var
Suits : array[1..4] of String; // A list of 4 playing card suit names

begin
Suits[1] := 'Hearts'; // Assigning to array index 1
Suits[2] := 'Diamonds'; // Assigning to array index 2
Suits[3] := 'Clubs'; // Assigning to array index 3
Suits[4] := 'Spades'; // Assigning to array index 4
end;

The array defined above has indexes 1 to 4 (1..4). The two dots indicate a range. We have told Delphi that the array elements will be string variables. We could equally have defined integers or decimals.

For more on arrays, see the Arrays tutorial.

Records
Records are like arrays in that they hold collections of data. However, records can hold a mixture of data types. Ther are a very powerful and useful feature of Delphi, and one that distinguishes Delphi from many other languages.

Normally, you will define your own record structure. This definition is not itself a variable. It is called a data type (see Types for further on this). It is defined in a type data section. By convention, the record type starts with a T to indicate that it is a type not real data (types are like templates). Let us define a customer record:

type
TCustomer Record
firstName : string[20];
lastName : string[20];
age : byte;
end;

Note that the strings are suffixed with [20]. This tells Delphi to make a fixed space for them. Since strings can be a variable length, we must tell Delphi so that it can make a record of known size. Records of one type always take up the same memory space.

Let us create a record variable from this record type and assign to it:

var
customer : TCustomer; // Our customer variable
begin
customer.firstName := 'Fred'; // Assigning to the customer record
customer.lastName := 'Bloggs';
customer.age := 55;
end;

customer.firstName is now set to 'Fred'
customer.lastName is now set to 'Bloggs'
customer.age is now set to 55

Notice how we do not use an index to refer to the record elements. Records are very friendly - we use the record element by its name, separated from the record name by a qualifying dot. See the Records tutorial for further on records.

Objects
Objects are collections of both data and logic. They are like programs, but also like data structures. They are the key part of the Object oriented nature of Delphi. See the Object orientation tutorial for more on this advanced topic.


Other data types
The remaining main object types in Delphi are a mixed bunch:

Files
File variables represent computer disk files. You can read from and write to these files using file access routines. This is a complex topic covered in Files.

Pointers
Pointers are also the subject of an advanced topic - see Pointer reference. They allow variables to be indirectly referenced.

Variants
Variants are also an advanced topic - see Variant. They allow the normal Delphi rigid type handling to be avoided. Use with care!

Storing data in computer programs

Storing data in computer programs
For those new to computer programming, data and code go hand in hand. You cannot write a program of any real value without lines of code, or without data. A Word Processor program has logic that takes what the user types and stores it in data. It also uses data to control how it stores and formats what the user types and clicks.

Data is stored in the memory of the computer when the program runs (it can also be stored in a file, but that is another matter beyond the scope of this tutorial). Each memory 'slot' is identified by a name that the programmer chooses. For example LineTotal might be used to name a memory slot that holds the total number of lines in a Word Processor document.

The program can freely read from and write to this memory slot. This kind of data is called a Variable. It can contain data such as a number or text. Sometimes, we may have data that we do not want to change. For example, the maximum number of lines that the Word Processor can handle. When we give a name to such data, we also give it its permanent value. These are called constants.

exception handling

It is imperative that the exception handling code is fail safe. An important rule to remember is

The last exception thrown in a try-catch-finally block is
the exception that will be propagated up the call stack.
All earlier exceptions will disappear.
If an exception is thrown from inside a catch or finally block, this exception may hide the exception caught by that block. This is misleading when trying to determine the cause of the error.

Below is a classic example of non-fail-safe exception handling:

InputStream input = null;

try{

input = new FileInputStream("myFile.txt");

//do something with the stream

} catch(IOException e){
throw new WrapperException(e);
} finally {
try{
input.close();
} catch(IOException e){
throw new WrapperException(e);
}
}
If the FileInputStream constructor throws a FileNotFoundException, what do you think will happen?

First the catch block is executed. This block just rethrows the exception wrapped in a WrapperException.

Second the finally block will be executed which closes the input stream. However, since a FileNotFoundException was thrown by the FileInputStream constructor, the "input" reference will be null. The result will be a NullPointerException thrown from the finally block. The NullPointerException is not caught by the finally block's catch(IOException e) clause, so it is propagated up the call stack. The WrapperException thrown from the catch block will just disappear!

The correct way to handle this situation is course to check if references assigned inside the try block are null before invoking any methods on them. Here is how that looks:

InputStream input = null;

try{

input = new FileInputStream("myFile.txt");

//do something with the stream

} catch(IOException e){ //first catch block
throw new WrapperException(e);
} finally {
try{
if(input != null) input.close();
} catch(IOException e){ //second catch block
throw new WrapperException(e);
}
}
But even this exception handling has a problem. Let's pretend the file exists, so the "input" reference now points to a valid FileInputStream. Let's also pretend that an exception is thrown while processing the input stream. That exception is caught in the catch(IOException e) block. It is then wrapped and rethrown. Before the wrapped exception is propagated up the call stack, the finally clause is executed. If the input.close() call fails, and an IOException is thrown, then it is caught, wrapped and rethrown. However, when throwing the wrapped exception from the finally clause, the wrapped exception thrown from the first catch block is again forgotten. It disappears. Only the exception thrown from the second catch block is propagated up the call stack.

As you can see, fail safe exception handling is not always trivial. The InputStream processing example is not even the most complex example you can come across. Transactions in JDBC have somewhat more error possibilities. Exceptions can occur when trying to commit, then rollback, and finally when you try to close the connection. All of these possible exceptions should be handled by the exception handling code, so none of them make the first exception thrown disappear. One way to do so is to make sure that the last exception thrown contains all previously thrown exceptions. That way they are all available to the developer investigating the error cause. This is how our Java persistence API, Mr Persister, implements transaction exception handling.

Exception Wrapping

Exception wrapping is wrapping is when you catch an exception, wrap it in a different exception and throw that exception. Here is an example:

try{
dao.readPerson();
} catch (SQLException sqlException) {
throw new MyException("error text", sqlException);
}
The method dao.readPerson() can throw an SQLException. If it does, the SQLException is caught and wrapped in a MyException. Notice how the SQLException (the sqlException variable) is passed to the MyException's constructor as the last parameter.

Exception wrapping is a standard feature in Java since JDK 1.4. Most (if not all) of Java's built-in exceptions has constructors that can take a "cause" parameter. They also have a getCause() method that will return the wrapped exception.

Why Use Exception Wrapping?

The main reason one would use exception wrapping is to prevent the code further up the call stack from having to know about every possible exception in the system. There are two main reasons for this.

The first reason is, that declared exceptions aggregate towards the top of the call stack. If you do not wrap exceptions, but instead pass them on by declaring your methods to throw them, you may end up with top level methods that declare many different exceptions. Declaring all these exceptions in each method back up the call stack becomes tedious.

The second reason is that you may not want your top level components to know anything about the bottom level components, nor the exceptions they throw. For instance, the purpose of DAO interfaces and implementations is to abstract the details of data access away from the rest of the application. Now, if your DAO methods throw SQLException's then the code using the DAO's will have to catch them. What if you change to an implementation that reads the data from a web service instead of from a database? Then you DAO methods will have to throw both RemoteException and SQLException. And, if you have a DAO that reads data from a file, you will need to throw IOException too. That is three different exceptions, each bound to their own DAO implementation.

To avoid this your DAO interface methods can throw DaoException. In each implementation of the DAO interface (database, file, web service) you will catch the specific exceptions (SQLException, IOException, RemoteException), wrap it in a DaoException, and throw the DaoException. Then code using the DAO interface will only have to deal with DaoException's. It does not need to know anything about what data access technology is used in the various implementations.

check or uncheck exceptions

In Java there are basically two types of exceptions: Checked exceptions and unchecked exceptions. C# only has unchecked exceptions. The differences between checked and unchecked exceptions are:
  1. Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.
  2. Checked exceptions in Java extend the java.lang.Exception class. Unchecked exceptions extend the java.lang.RuntimeException.
There are many arguments for and against both checked and unchecked, and whether to use checked exceptions at all. I will go through the most common arguments throughout this text. Before I do so, let me just make one thing clear:
Checked and unchecked exceptions are functionally equivalent. There is nothing you can do with checked exceptions that cannot also be done with unchecked exceptions, and vice versa.
Regardless of your choice between checked and unchecked exceptions it is a matter of personal or organisational style. None is functionally better than the other.


A Simple Example

Before discussing the advantages and disadvantages of checked and unchecked exceptions I will show you the difference in the code they make. Here is a method that throws a checked exception, and another method that calls it:

public void storeDataFromUrl(String url){
        try {
            String data = readDataFromUrl(url);
        } catch (BadUrlException e) {
            e.printStackTrace();
        }
    }

    public String readDataFromUrl(String url)
    throws BadUrlException{
        if(isUrlBad(url)){
            throw new BadUrlException("Bad URL: " + url);
        }

        String data = null;
        //read lots of data over HTTP and return
        //it as a String instance.

        return data;
    }

As you can see the readDataFromUrl() method throws a BadUrlException. I have created BadUrlException myself. BadUrlException is a checked exception because it extends java.lang.Exception:

public class BadUrlException extends Exception {
        public BadUrlException(String s) {
            super(s);
        }
    }

If storeDataFromUrl() wants to call readDataFromUrl() it has only two choices. Either it catches the BadUrlException or propagates it up the call stack. The storeDataFromUrl() listed above catches the exception. This storeDataFromUrl() implementation propagates the BadUrlException instead:

public void storeDataFromUrl(String url)
    throws BadUrlException{
        String data = readDataFromUrl(url);
    }

Notice how the try catch block is gone and a "throws BadUrlException" declaration is added instead. Now, let's see how it looks with unchecked exceptions. First I change the BadUrlException to extend java.lang.RuntimeException instead:

public class BadUrlException extends RuntimeException {
        public BadUrlException(String s) {
            super(s);
        }
    }

Then I change the methods to use the now unchecked BadUrlException:

public void storeDataFromUrl(String url){
        String data = readDataFromUrl(url);
    }

    public String readDataFromUrl(String url) {
        if(isUrlBad(url)){
            throw new BadUrlException("Bad URL: " + url);
        }

        String data = null;
        //read lots of data over HTTP and
        //return it as a String instance.

        return data;
    }

Notice how the readDataFromUrl() method no longer declares that it throws BadUrlException. The storeDataFromUrl() method doesn't have to catch the BadUrlException either. The storeDataFromUrl() method can still choose to catch the exception but it no longer has to, and it no longer has to declare that it propagates the exception.


Checked or Unchecked?

Now that we have seen the difference in code between checked and unchecked exceptions, let's dive into the arguments for and against both.
Some Java books(*) covering exceptions advice you to use checked exceptions for all errors the application can recover from, and unchecked exceptions for the errors the application cannot recover from. In reality most applications will have to recover from pretty much all exceptions including NullPointerException, IllegalArgumentExceptions and many other unchecked exceptions. The action / transaction that failed will be aborted but the application has to stay alive and be ready to serve the next action / transaction. The only time it is normally legal to shut down an application is during startup. For instance, if a configuration file is missing and the application cannot do anything sensible without it, then it is legal to shut down the application.
(*) Suns Java Tutorial does for one.
My advice to you is to use either only checked exceptions or only unchecked exceptions. Mixing exception types often results in confusion and inconsistent use. Of course you should be pragmatic. Do what makes sense in your situation.
Below is a list of the most common arguments for and against checked and unchecked exceptions. An argument in favor of one type of exceptions is usually against the other type (pro-checked = con-unchecked, pro-unchecked = con-checked). Therefore the arguments are only listed as either in favour of checked or unchecked exceptions.


  1. Pro Checked Exceptions:
    Compiler enforced catching or propagation of checked exceptions make it harder to forget handling that exception.
  2. Pro Checked Exceptions:
    Unchecked exceptions makes it easier to forget handling errors since the compiler doesn't force the developer to catch or propagate exceptions (reverse of 1).
  3. Pro Unchecked Exceptions:
    Checked exceptions that are propagated up the call stack clutter the top level methods, because these methods need to declare throwing all exceptions thrown from methods they call.
  4. Pro Checked Exceptions:
    When methods do not declare what unchecked exceptions they may throw it becomes more difficult to handle them.
  5. Pro Unchecked Exceptions:
    Checked exceptions thrown become part of a methods interface and makes it harder to add or remove exceptions from the method in later versions of the class or interface.


Each of the arguments also have counter arguments which will be discussed as I go through the argument in the following sections.

Argument 1 (Pro Checked Exceptions):

Compiler enforced catching or propagation of checked exceptions makes it harder to forget the handling of that exception.

Counter-argument:

When being forced to catch or propagate many exceptions developers risk acting sloppily, and just write

try{
   callMethodThatThrowsException();
catch(Exception e){
}

and thus effectively ignore the error.

Argument 2 (Pro Checked Exceptions):

Unchecked exceptions makes it easier to forget handling errors since the compiler doesn't force the developer to catch or propagate exceptions.

Counter-argument 1:

It's not any worse than the sloppy exception handling tendency when being forced to handle or propagate checked exceptions.

Counter-argument 2:

On a recent larger project we decided to go with unchecked exceptions. My personal experience from that project is this: When using unchecked exceptions any method can potentially throw exceptions. Thus I was always reasonably conscious about exceptions no matter what parts of the code I was working on. Not only when checked exceptions were declared.
In addition many of the standard Java API methods that do not declare any checked exceptions may still throw unchecked exceptions like NullPointerException or InvalidArgumentException. Your application will still need to handle these unchecked exceptions. You could argue that the fact that there are checked exceptions makes it easy to forget handling the unchecked exceptions because they are not declared.

Argument 3 (Pro Unchecked Exceptions):

Checked exceptions that are propagated up the call stack clutter the top level methods, because these methods need to declare throwing all exceptions thrown from methods they call. That is. the declared exceptions are aggreated up the methods in the call stack. Example:

public long readNumberFromUrl(String url)
    throws BadUrlExceptions, BadNumberException{
        String data = readDataFromUrl(url);
        long number = convertData(data);
        return number;
    }

    private String readDataFromUrl(String url)
    throws BadUrlException {
       //throw BadUrlException if url is bad.
       //read data and return it.
    }

    private long convertData(String data)
    throws BadNumberException{
        //convert data to long.
        //throw BadNumberException if number isn't within valid range.
    }

As you can see the readNumberFromUrl() needs to declare throwing both the BadUrlException and the BadNumberException that are thrown from the readDataFromUrl() and converData() methods. Imagine how many exceptions would need to be declared at the top level methods of an application with thousands of classes. This can make checked exception propagation a real pain.

Counter-argument 1:

The exception declaration aggregation rarely happens in real applications. Often developers will use exception wrapping instead. Here is how that could look:

public void readNumberFromUrl(String url)
    throws ApplicationException{
        try{
            String data = readDataFromUrl(url);
            long number = convertData(data);
        } catch (BadUrlException e){
            throw new ApplicationException(e);
        } catch (BadNumberException e){
            throw new ApplicationException(e);
        }
    }

As you can see the readNumberFromUrl() method now only declares throwing ApplicationException. The exceptions BadUrlException and BadNumberException are caught and wrapped in a more general ApplicationException. This way exception wrapping avoids exception declaration aggregation.
My personal opinion is, that if all you do is to wrap the exception and not provide any extra information, why wrap it at all? The try-catch block is just extra code that doesn't do anything. It would be easier to just make the ApplicationException, BadUrlException and BadNumberException be unchecked exceptions. Here is an unchecked version of the above code:

public void readNumberFromUrl(String url){
        String data = readDataFromUrl(url);
        long number = convertData(data);
    }

It is still possible to wrap unchecked exceptions if you should want to. Below is a wrapping edition of the unchecked code. Notice how the readNumberFromUrl() method does not declare throwing the ApplicationException even if it throws it.

public void readNumberFromUrl(String url)
        try{
            String data = readDataFromUrl(url);
            long number = convertData(data);
        } catch (BadUrlException e){
            throw new ApplicationException(
                "Error reading number from URL", e);
        } catch (BadNumberException e){
            throw new ApplicationException(
                "Error reading number from URL", e);
        }
    }

Counter-argument 2:

Another commonly used technique to avoid exception declaration aggregation up the call stack of an application is to create an application base exception. All exceptions thrown in the application must be a subclass of the base exception. All methods throwing exceptions need only declare to throw the base exception. As you know a method throwing Exception may also throw any subclass of Exception. Here is how that could look:

public long readNumberFromUrl(String url)
    throws ApplicationException {
        String data = readDataFromUrl(url);
        long number = convertData(data);
        return number;
    }

    private String readDataFromUrl(String url)
    throws BadUrlException {
       //throw BadUrlException if url is bad.
       //read data and return it.
    }

    private long convertData(String data)
    throws BadNumberException{
        //convert data to long.
        //throw BadNumberException if number isn't within valid range.
    }


    public class ApplicationException extends Exception{ }
    public class BadNumberException   extends ApplicationException{}
    public class BadUrlException      extends ApplicationException{}

Notice how the BadNumberException and BadUrlException are no longer declared thrown nor caught and wrapped. They are subclasses of the ApplicationException so they will get propagated up the call stack.
My opinion is the same as with exception wrapping: If all methods in the application just declares throwing the ApplicationException (base exception), why not just make the ApplicationException unchecked and save some try-catch blocks and throws ApplicationExceptions clauses? 

Argument 4 (Pro Checked Exceptions)

When methods do not declare what unchecked exceptions they may throw it becomes more difficult to handle them. Without declaration you cannot know which exceptions the method may throw. Thus you may not know how to handle them properly. Except of course, if you have access to the code and can see there what exceptions may be thrown from the method.

Counter-argument:

In most cases you cannot do anything about the exception except showing an error message to the user, write a message to the log, and/or rollback the transaction etc. No matter what exception occurs you will in many situations handle it the same way. Because of this applications often have a few central and general pieces of error handling code. Therefore it is not so important to know exactly what exceptions may be thrown.

Argument 5 (Pro Unchecked Exceptions)

Checked exceptions declared on methods become part of a the class or interface contract. This makes it harder to add new exceptions to the method later without breaking the contract.

Counter-argument

This is not a problem if the method uses a base exception. New exceptions can be thrown at will if the method declares throwing the base exception. The only requirement is that the new exceptions thrown are subclasses of the base exception.
Again, what is the value of having all methods that may throw exceptions declare throwing the same base exception? Does it enable you to handle the exceptions any better than if you knew the methods might throw an unchecked exception?


Summary

I used to be in favor of checked exceptions but recently I have begun to change my mind. Personalities like Rod Johnson (Spring Framework), Anders Hejlsberg (father of C#), Joshua Bloch (Effective Java, item 41: Avoid unnecessary use of checked exceptions) and others have made me rethink the real benefit of checked exceptions. Lately we have tried using unchecked exceptions on a larger project, and they have worked out just fine. The error handling is centralized in a few classes. Here and there we have had to do local error handling instead of propagating the exception to the main error handling code. But it is not in very many places. Our code has become somewhat more readable now that there aren't try-catch blocks all over the code. In other words, there are a lot less no-benefit catch-rethrow try-catch blocks in the code than with checked exceptions. All in all I would recommend using unchecked exceptions. At least give it a try on a project. I have summarized the reasons below:
  • Unchecked exceptions do not clutter the code with unnecessary try-catch blocks.
  • Unchecked exceptions do not clutter the method declarations with aggregated exception declarations.
  • The argument that you easier forget to handle unchecked exceptions is not valid in my experience.
  • The argument that it is harder to know how to handle undeclared exceptions is not valid in my experience.
  • Unchecked exceptions avoids versioning problems altogether.
You or your project will have to make your own decisions about whether to use checked or unchecked exceptions, or both. Here is a list of resources that also discusses the decision between checked and unchecked exceptions.

exception hierarchis

In Java and in C# exceptions can be categorized into hierarchies. The hierarchy is created by having one (or more) exception extend another exception. The first exception becomes a subclass of the second. In Java FileNotFoundException is a subclass of IOException. Here is how a custom exception looks in Java code:
public class MyException extends Exception{
    //constructors etc.
}
As you can see there isn't much to it. The advantage of exception hierarchies is that if you decide to catch (using try-catch) a certain exception in the hierarchy, then you will automatically also catch all subclasses of that exception too. In other words, you will catch all exceptions from that certain exception and down the hierarchy. In the example with FileNotFoundException, if you catch IOException which is the superclass of FileNotFoundException, you will also catch FileNotFoundException.

Multiple Catch Blocks

As you may know already it is possible to have several catch blocks for the same try-block. This is usually the case if the code inside the try-block throws more than one type of exception. But, multiple catch blocks can also be used in the case where all the exceptions thrown inside the try-block are the same type or subclasses of that type. This code illustrates that:
try{
    //call some methods that throw IOException's
} catch (FileNotFoundException e){
} catcy (IOException e){
}
Remember that the first catch-block a thrown exception matches will handle that exception. In this example all IOExceptions are being handled by the catch(IOException e) except for FileNotFoundException. The fact that FileNotFoundException is a subclass of IOException gives us the choice of either treating all IOExceptions the same, or catch some of IOExceptions subclasses individually, as is done in the code example above. If the catch(FileNotFoundException e) block is removed any FileNotFoundException will be caught by the catch(IOException e) block, since FileNotFoundException is a subclass of IOException.

Throws Clauses

If a method can throw either a certain exception A, or any subclasses of A (Asub), then it is enough to declare in the method declaration that the method throws A. It is then allowed to throw subclasses of A from the method too. Here is an example:
public void doSomething() throws IOException{
}
You are allowed to declare the subclasses in the throws clause of the method, even if you don't really need to. It can make the code easier to read and understand for the next developer to look at it. Here is an example:
public void doSomething() throws IOException, FileNotFoundException{
}
As long as the superclass of any declared exception is also declared thrown, it doesn't have any effect on the code to include the throwing of the subclass. In the example above it has no real effect that FileNotFoundException is declared thrown when IOException is also declared. When you catch IOException you also catch FileNotFoundException. It is still possible to handle the two exceptions with each their own catch-block as shown earlier, even if only the superclass is declared thrown.

Designing Exception Hierarchies

When designing exception hieararchies for an API or application it is a good idea to create a base exception for that API or application. For instance, in Mr. Persister, our Java Persistence / ORM API the base exception is called PersistenceException. This base exception makes it possible to catch and handle all exceptions thrown by Mr. Persister in the same catch block.
If you need more granularity on the exceptions thrown, for instance because you think the exceptions may be handled differently, then add new exceptions as subclasses of your API or application base exception. That way users have the choice of either catching the specific exceptions, or just the base exception. In Mr. Persister we could add a ConnectionOpenException, QueryException, UpdateException, CommitException, and ConnectionCloseException as subclasses of PersistenceException. If the users of Mr. Persister wanted to handle a ConnectionOpenException differently than a QueryException or a ConnectionCloseException, they could catch those exceptions and handle them differently. If not, the user could just catch PersistenceException and handle all exceptions uniformly.
You can subdivide the exceptions more by add more levels to the hierarchy. For instance, you may want to distinguish between an exception thrown because the URL to the database is wrong, and an exception thrown because the database is not running. In that case you could create two exceptions called DatabaseURLException and DatabaseNotRespondingException, which both extends the ConnectionOpenException. Then users can catch the two different exceptions and respond differently to them. This exception hierarchy looks like this:

Example Exception Hieararchy 


Summary

In this text we have seen that exception hierarchies can be created by subclassing exception classes. It is a good idea to create a base exception for your API or application, and have all other exceptions subclass this base exception. Individual subclasses makes it possible (but not obligatory) to catch and handle these individual exceptions differently. You should create individual exceptions only for errors that can actually be handled differently.

basic exception handling

This text summarizes the basics of how try-catch-finally clause error handling works. The examples are in Java, but the rules are the same for C#. The only difference between Java and C# exceptions is that C# doesn't have checked exceptions. Checked and unchecked exceptions are explained in more detail in a different text.
Exceptions are used in a program to signal that some error or exceptional situation has occurred, and that it doesn't make sense to continue the program flow until the exception has been handled. A method may throw an exception for many reasons, for instance if the input parameters are invalid (negative when expecting positive etc.).

The Call Stack Explained

This text refers to the concept the "call stack" in several places. By the call stack is meant the sequence of method calls from the current method and back to the Main method of the program. If a method A calls B, and B calls C then the call stack looks like this:
A
    B
    C
When method C returns the call stack only contains A and B. If B then calls the method D, then the call stack looks like this:
A
    B
    D
Understanding the call stack is important when learning the concept of exception propagation. Exception are propagated up the call stack, from the method that initially throws it, until a method in the call stack catches it. More on that later.

Throwing Exceptions

If a method needs to be able to throw an exception, it has to declare the exception(s) thrown in the method signature, and then include a throw-statement in the method. Here is an example:
public void divide(int numberToDivide, int numberToDivideBy)
    throws BadNumberException{
        if(numberToDivideBy == 0){
            throw new BadNumberException("Cannot divide by 0");
        }
        return numberToDivide / numberToDivideBy;
    }
When an exception is thrown the method stops execution right after the "throw" statement. Any statements following the "throw" statement are not executed. In the example above the "return numberToDivide / numberToDivideBy;" statement is not executed if a BadNumberException is thrown. The program resumes execution when the exception is caught somewhere by a "catch" block. Catching exceptions is explained later.
You can throw any type of exception from your code, as long as your method signature declares it. You can also make up your own exceptions. Exceptions are regular Java classes that extends java.lang.Exception, or any of the other built-in exception classes. If a method declares that it throws an exception A, then it is also legal to throw subclasses of A.

Catching Exceptions

If a method calls another method that throws checked exceptions, the calling method is forced to either pass the exception on, or catch it. Catching the exception is done using a try-catch block. Here is an example:
public void callDivide(){
        try {
            int result = divide(2,1);
            System.out.println(result);
        } catch (BadNumberException e) {
            //do something clever with the exception
            System.out.println(e.getMessage());
        }
        System.out.println("Division attempt done");
    }
The BadNumberException parameter e inside the catch-clause points to the exception thrown from the divide method, if an exception is thrown.
If no exeception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored. It will not be executed.
If an exception is thrown inside the try-block, for instance from the divide method, the program flow of the calling method, callDivide, is interrupted just like the program flow inside divide. The program flow resumes at a catch-block in the call stack that can catch the thrown exception. In the example above the "System.out.println(result);" statement will not get executed if an exception is thrown fromt the divide method. Instead program execution will resume inside the "catch (BadNumberException e) { }" block.
If an exception is thrown inside the catch-block and that exception is not caught, the catch-block is interrupted just like the try-block would have been.
When the catch block is finished the program continues with any statements following the catch block. In the example above the "System.out.println("Division attempt done");" statement will always get executed.

Propagating Exceptions

You don't have to catch exceptions thrown from other methods. If you cannot do anything about the exception where the method throwing it is called, you can just let the method propagate the exception up the call stack to the method that called this method. If you do so the method calling the method that throws the exception must also declare to throw the exception. Here is how the callDivide() method would look in that case.
public void callDivide() throws BadNumberException{
        int result = divide(2,1);
        System.out.println(result);
    }
Notice how the try-catch block is gone, and the callDivide method now declares that it can throw a BadNumberException. The program execution is still interrupted if an exception is thrown from the divide method. Thus the "System.out.println(result);" method will not get executed if an exception is thrown from the divide method. But now the program execution is not resumed inside the callDivide method. The exception is propagated to the method that calls callDivide. Program execution doesn't resume until a catch-block somewhere in the call stack catches the exception. All methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated.

Example: Catching IOException's

If an exception is thrown during a sequence of statements inside a try-catch block, the sequence of statements is interrupted and the flow of control will skip directly to the catch-block. This code can be interrupted by exceptions in several places:
public void openFile(){
        try {
            // constructor may throw FileNotFoundException
            FileReader reader = new FileReader("someFile");
            int i=0;
            while(i != -1){
                //reader.read() may throw IOException
                i = reader.read();
                System.out.println((char) i );
            }
            reader.close();
            System.out.println("--- File End ---");
        } catch (FileNotFoundException e) {
            //do something clever with the exception
        } catch (IOException e) {
            //do something clever with the exception
        }
    }
If the reader.read() method call throws an IOException, the following System.out.println((char) i ); is not executed. Neither is the last reader.close() or the System.out.println("--- File End ---"); statements. Instead the program skips directly to the catch(IOException e){ ... } catch clause. If the new FileReader("someFile"); constructor call throws an exception, none of the code inside the try-block is executed.

Example: Propagating IOException's

This code is a version of the previous method that throws the exceptions instead of catching them:
public void openFile() throws IOException {
        FileReader reader = new FileReader("someFile");
        int i=0;
        while(i != -1){
            i = reader.read();
            System.out.println((char) i );
        }
        reader.close();
        System.out.println("--- File End ---");
    }
If an exception is thrown from the reader.read() method then program execution is halted, and the exception is passed up the call stack to the method that called openFile(). If the calling method has a try-catch block, the exception will be caught there. If the calling method also just throws the method on, the calling method is also interrupted at the openFile() method call, and the exception passed on up the call stack. The exception is propagated up the call stack like this until some method catches the exception, or the Java Virtual Machine does.

Finally

You can attach a finally-clause to a try-catch block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or catch block. If your code has a return statement inside the try or catch block, the code inside the finally-block will get executed before returning from the method. Here is how a finally clause looks:
public void openFile(){
        FileReader reader = null;
        try {
            reader = new FileReader("someFile");
            int i=0;
            while(i != -1){
                i = reader.read();
                System.out.println((char) i );
            }
        } catch (IOException e) {
            //do something clever with the exception
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    //do something clever with the exception
                }
            }
            System.out.println("--- File End ---");
        }
    }
No matter whether an exception is thrown or not inside the try or catch block the code inside the finally-block is executed. The example above shows how the file reader is always closed, regardless of the program flow inside the try or catch block.
Note: If an exception is thrown inside a finally block, and it is not caught, then that finally block is interrupted just like the try-block and catch-block is. That is why the previous example had the reader.close() method call in the finally block wrapped in a try-catch block:
} finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    //do something clever with the exception
                }
            }
            System.out.println("--- File End ---");
        }
That way the System.out.println("--- File End ---"); method call will always be executed. If no unchecked exceptions are thrown that is. More about checked and unchecked in a later chapter.
You don't need both a catch and a finally block. You can have one of them or both of them with a try-block, but not none of them. This code doesn't catch the exception but lets it propagate up the call stack. Due to the finally block the code still closes the filer reader even if an exception is thrown.
public void openFile() throws IOException {
        FileReader reader = null;
        try {
            reader = new FileReader("someFile");
            int i=0;
            while(i != -1){
                i = reader.read();
                System.out.println((char) i );
            }
        } finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    //do something clever with the exception
                }
            }
            System.out.println("--- File End ---");
        }
    }
Notice how the catch block is gone.

Catch or Propagate Exceptions?

You might be wondering whether you should catch or propate exceptions thrown in your program. It depends on the situation. In many applications you can't really do much about the exception but tell the user that the requested action failed. In these applications you can usually catch all or most exceptions centrally in one of the first methods in the call stack. You may still have to deal with the exception while propagating it though (using finally clauses). For instance, if an error occurs in the database connection in a web application, you may still have to close the database connection in a finally clause, even if you can't do anything else than tell the user that the action failed. How you end up handling exceptions also depends on whether you choose checked or unchecked exceptions for your application. There is more on that in other texts in the error handling trail.

VM Ware

VM Ware merupakan sebuah aplikasi yang sangat berguna untuk mencoba produk-produk baru atau yang masuh beta agar tidak mengotori PC kita.
VM Ware ini berfungsi sebagai komputer kedua kita namun komputer kedua kita ini berjalan didalam komputer utama kita.

bagi para programer ini benar2 sangat berguna untuk membuat sebuah program yang memiliki fitur client sever atau tidak stayalone

Friday, February 25, 2011

Blogging from iGoogle and Gmail - Blogger Help

Blogging from iGoogle and Gmail - Blogger Help

it's cool..
I can post my article from my chrom and without visit my blog

Install TangoCMS

TangoCMS merupakan salah satu dari sekian banyak CMS gratisn dan memiliki beberapa kelebihan dibanding yang lainnya yaitu opensource dan kita bisa dengan mudah meng editnya.

namun terkadang terjadi error dalam proses instalasinya jika kita menggunakan webhosting.

Install TangoCMS

TangoCMS merupakan salah satu dari sekian banyak CMS gratisn dan memiliki beberapa kelebihan dibanding yang lainnya yaitu opensource dan kita bisa dengan mudah meng editnya.

namun terkadang terjadi error dalam proses instalasinya jika kita menggunakan webhosting.

Variabel Dan Operator Pada JAVA

Variable
Variabel adalah satuan yang dipakai oleh program sebagai basis penyimpanan. Penggunaan variabel harus dilakukan lebih dahulu melalui deklarasi variabel, yaitu menentukan tipe dan nama variabel yang digunakan.

Tipe
Keterangan
short
short int, bilangan bulat 16 bit
int
integer, bilangan bulat 32 bit
long
long integer, bilangan bulat 64 bit
byte
bilangan bulat 8 bit
float
bilangan pecahan 32 bit
double
bilangan pecahan 64 bit dengan presisi ganda (2xfloat)
char
karakter 16 bit
boolean
mempunyai nilai true atau false

Operator Aritmatika
Seperti juga bahasa pemrograman lainnya, java mempunyai operator aritmatika seperti +,-,*, / dan % (modulo).

Operator bit per bit
Variable tipe long, int, short, byte, dan char dapat mempunyai operator yang bereaksi secara bit per bit.
Operator
Nama
Deskripsi
~
NOT
Mengubah setiap 0 menjadi 1 dan 1 menjadi 0
&
AND
1 & 1 = 1, selain itu hasil selalu 0
|
OR
0 | 0 = 0, selain itu hasil selalu 1
^
XOR
0^0=0        1^1=0
0^1=1        1^0=1

Komentar Dan Kata Kunci Pada JAVAa

Komentar
Pemberian komentar dalam program adalah penting karena akan memperjelas alur program serta memberikan dokumentasi yang jelas dan mempunyai arti.

System.out.println(“Halo”); //mencetak kata halo
/* semua yang ada didalam ini
    adalah komentar, sebanyak
    3 baris */

Kata Kunci (Reserved Words)
abstract
default
if
package
syschronized
boolean
do
implements
private
this
break
double
import
protected
throw
byte
else
instanceof
public
throws

extends
int

transient
case
false
interface
return
true
catch
final


try
char
finally
long
short

class
float
native
static
void
const
for
new
super
volatile
continue
goto
null
switch
while