Exception Handling In Java

Exception Handling In Java

Exception Handling In Java

 

Exception Handling In Java. Without Using Exception Handling , when there is an error occur either cause by the User or the program itself. Java will totally shut down the whole Program.,and the remaining code subsequently  will not be executed. But if we use “Exception Handling” we might be able to catch an Error, and continue executing the remaining subsequent program.

In this Sample code, the Program will ask the User to  enter an Integer. If the User enter an Integer it will print out “You have enter an integer”

if 

the User enter anything except an Integer, the program will throw an Exception and print out  “You must enter an integer”,


package exceptions;
import java.util.*;

public class exceptDemo {

	public static void main(String[] args) {
		
		
		
		
		
		Scanner input_01 =  new Scanner(System.in);
		Scanner input_02 = new Scanner(System.in);
		
	
		
		try{
		
		// ask the User to enter and Input
		System.out.println("Please enter a number in integer");
		
		int number_01 = input_01.nextInt();
	
	    System.out.println("You have enter an integer");
		
		}
		
		catch(Exception e)
		{
			
			System.out.println("Wrong Input try again !");
			
		   System.out.println("You must enter an integer");	
			
			
		}
		
		
		
	}

}


 



package exception2;

public class anotherException {

	public static void main(String[] args) {
	   
		try{
		int a[]={1,2,3,4,5};
		
		
		for(int x =0; x <= 7 ; x++){
		
	
		  System.out.print(a[x]);
			
			
			
		}
		
		}
		
		catch(ArrayIndexOutOfBoundsException e){
			
			// Get the Error Message
			System.out.println(e.getMessage());
			
			
			
		}
		
		

	}

}


How to check whether a user string input in Java

  • Use the same Exception e Handling but change “int number_01 = input_01.nextInt(); ” to “String line_01 = input_01.nextLine();”

package exceptions;
import java.util.*;

public class exceptDemo {

	public static void main(String[] args) {
		
		
		
		
		
		Scanner input_01 =  new Scanner(System.in);
		Scanner input_02 = new Scanner(System.in);
		
	
		
		try{
		
		// ask the User to enter and Input
		System.out.println("Please enter a String");
		
		String line_01 = input_01.nextLine();
	
	    System.out.println("You have enter a String");
		
		}
		
		catch(Exception e)
		{
			
			System.out.println("Wrong Input try again !");
			
		   System.out.println("You must enter an integer");	
			
			
		}
		
	
		
	
		

		
		
		
		
	}

}


Well tats is Exception Handling In Java

Check out the list of Exception Error Handling here
Check out Overriding in Java here

Leave a Reply

Your email address will not be published. Required fields are marked *

sixteen + nineteen =