Wednesday, February 20, 2019

Lesson 5 - Try catch

Create a new class name five.
Type these lines.
public static void main(String args[]) {
          int so=0;     
          so=Integer.parseInt("88"); 

          System.out.println("Integer number is: "+so);   
 
          int c=10+so;
          System.out.println("Sum result is: "+c);
}
Run to see result.

We cast a String to number, if for some reason, we can’t do this and get an error, programme will crash.
Add  text to string want to cast, for example, “88a”, run and see.

Eclipse show exception error.
To avoid this, Java use try catch to prevent programme from crash.
Add try catch to that code.
public static void main(String args[]) {
          int so=0;
     try{                
          so=Integer.parseInt("88a"); 

     System.out.println("Integer number is: "+so);   
     } catch (Exception e) {       
     System.out.println("Error when cast string to number");
     }
     int c=10+so;
     System.out.println("Sum result is: "+c);}

When we run, programme print the line Sum result is: 10”, and the error notification we type before.
This different with there no try catch, programme can’t print anything.
When command in try get error, comand in catch run, other codes outside try catch run normally.
Remove text add to cast string, run again.

In Android, if codes need try catch, it will recommend we to add.

But sometime we have to add ourself, for example, get year from Edittext, if user enter invalid number, we use try catch to inform them.

No comments:

Post a Comment