Page 379 - CITS - Computer Software Application -TT
P. 379
COMPUTER SOFTWARE APPLICATION - CITS
throw The “throw” keyword is used to throw an exception.
The “throws” keyword is used to declare exceptions. It specifies that there
throws may occur an exception in the method. It doesn’t throw an exception. It is
always used with method signature.
Java Exception Handling Example
Let’s see an example of Java Exception Handling in which we are using a try-catch statement to handle the
exception.
JavaExceptionExample.java
public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){System.out.println(e);}
//rest code of the program
System.out.println(“rest of the code...”);
}
}
Test it Now
Output
Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
In the above example, 100/0 raises an ArithmeticException which is handled by a try-catch block.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:
1 A scenario where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1 int a=50/0;//ArithmeticException
2 A scenario where NullPointerException occurs
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
1 String s=null;
2 System.out.println(s.length());//NullPointerException
3 A scenario where NumberFormatException occurs
If the formatting of any variable or number is mismatched, it may result into NumberFormatException. Suppose we
have a string variable that has characters; converting this variable into digit will cause NumberFormatException.
1 String s=”abc”;
2 int i=Integer.parseInt(s);//NumberFormatException
4 A scenario where ArrayIndexOutOfBoundsException occurs
When an array exceeds to it’s size, the ArrayIndexOutOfBoundsException occurs. there may be other reasons to
occur ArrayIndexOutOfBoundsException. Consider the following statements.
366
CITS : IT&ITES - Computer Software Application - Lesson 101 - 108