Python try except else with example program

  • Please read below post to get an idea of try and except blocks in detail
  • Python try except example program
  • We will place all statements which are proven to generate exceptions in try block so that if any error occurred it will immediately enters into except and assign exception object to corresponding class.
  • If any exception occurs in try then except will be executed in order to handle the exception.
  • If no exception occurred in the try the it will executes else block.
  • So in Python exception handing else block will be executed if and only if no exceptions are occurred in try block and all the statements in try executed.
  • Lets see an example program on how can we use else in python exception handling
  • try-except-else 




#1: Write a python example program which explains usage of else block in exception handling of python programming.

  1. try:
  2.     x = int(input("enter 1st number: "))
  3.     y = int(input("enter 2nd number: "))
  4.     print(x/y)
  5.     string=input("enter some string: ")
  6.     print(string[8])
  7. except (IndexError, ZeroDivisionError) as e:
  8.     print("An error occurred :",e)
  9. else:
  10.     print("no error")

Output

  1. enter 1st number: 2
  2. enter 2nd number: 0
  3. An error occurred : division by zero

  4. enter 1st number: 2
  5. enter 2nd number: 1
  6. 2.0
  7. enter some string: python
  8. An error occurred : string index out of range

  9. enter 1st number: 2
  10. enter 2nd number: 1
  11. 2.0
  12. enter some string: python is very easy
  13. s
  14. no error  


python else example program

Python try except example program

  • Exceptions are the objects representing the logical errors that occur at run time.
  • When python script encounters any error at run time it will create python object.
  • So we need to handle this situation otherwise python program will terminates because of that run time error ( Exception Object).
  • So we can handle this by assigning this python exception object to corresponding python class.
  • For that Python provides try and except blocks to handle exceptions.
  • In try block we need to keep all the statements which may raise exceptions at run time.
  • except block will catch that exception and assigns to corresponding error class.
  • Lets see an example python program on exception handling using try and except blocks.




#1: Example Program to handle exception using try and except blocks in python programming.

  1. #use of try_catch in functions:
  2. def f():
  3.    x=int(input("enter some number: "))
  4.    print(x)

  5. try:
  6.     f()
  7.     print("no exception")
  8. except ValueError as e:
  9.     print("exception: ", e)
  10.     print("Rest of the Application")

Output

  1. enter some number: 2
  2. 2
  3. no exception
  4. >>> 



  5. enter some number: "python"
  6. exception:  invalid literal for int() with base 10: '"python"'
  7. Rest of the Application
  8. >>> 

try and except python example

How to Convert string to StringBuilder and vise versa in Java


  • We can Covert String to string builder in two ways
  1. Using constructor of StringBuilder(String s)
  2. Using append method of StringBuilder 
  • Lets see a java program to convert java String object to StringBuilder using constructor of StringBuilder class.

#1: Java program to convert string to StringBuilder using constructor of StringBuilder class.



  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: Java Program to convert String to StringBuilder
  7.  *
  8.  */
  9. public class StringBuilderDemo {

  10. public static void main(String[] args) {
  11. String str="java";
  12. StringBuilder sb = new StringBuilder(str);
  13. String s = sb.toString();
  14. System.out.println(s);
  15. StringBuilder stebldr= new StringBuilder("convert string to stringbuilder");
  16. String st = stebldr.toString();
  17. System.out.println(st);
  18. }

  19. }

Output

  1. java
  2. convert string to stringbuilder

#2: Java program to convert string to StringBuilder using append method of StringBuilder class.
  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: Java Program to convert String to StringBuilder
  7.  *
  8.  */
  9. public class StringBuilderDemo {

  10. public static void main(String[] args) {

  11. StringBuilder sb = new StringBuilder();
  12. sb.append("Java convert string to StringBuilder ");
  13. System.out.println(sb);
  14. String str= "Convert string to Stringbuilder" ;
  15. sb.append(str);
  16. System.out.println(sb);
  17. }

  18. }


Output

  1. Java convert string to StringBuilder 
  2. Java convert string to StringBuilder Convert string to Stringbuilder

  • We can Convert StringBuilder to String by using toString() method of StringBuilder class.
  • How to convert StringBuilder to String in java.


#3: Java program to convert string to StringBuilder using append method of StringBuilder class.

  1. package com.instanceofjava;
  2. /**
  3.  * @author www.Instanceofjava.com
  4.  * @category interview programs
  5.  * 
  6.  * Description: Java Program to convert StringBuilder to String
  7.  *
  8.  */
  9. public class StringBuilderDemo {

  10. public static void main(String[] args) {

  11. StringBuilder sb = new StringBuilder();
  12. sb.append("Java convert  StringBuilder to string");
  13. String str=sb.toString();
  14. System.out.println(str);
  15. String s= "Convert Stringbuilder to string " ;
  16. sb.append(s);
  17. String st=sb.toString();
  18. System.out.println(st);
  19. }

  20. }

Output

  1. Java convert  StringBuilder to string
  2. Java convert  StringBuilder to stringConvert Stringbuilder to string 


java program to convert string to string builder

Java Program to check a String is palindrome or not by ignoring its case


  • A palindrome is a word that reads the same backward or forward.
  • Lets see what if the characters in a palindrome string are in different case. i.e should not be case sensitive. 
  • So now we will see how to check a string is palindrome or not by ignoring its case.
  • Write a function which checks  that string is palindrome or not by converting the original string to lowercase or uppercase.
  • Method should return true if it is palindrome, return false if not a palindrome.


#1 : Java Program to check given string is palindrome or not by ignoring its case.

  1. package com.instanceofjava;

  2. public class CheckPalindrome {
  3. public static boolean isPalindrome(String str) {
  4. StringBuffer strone=new StringBuffer(str.toLowerCase());
  5. StringBuffer strtwo=new StringBuffer(strone);
  6.  
  7.   strone.reverse();
  8.  
  9.   System.out.println("Orginal String ="+strtwo);
  10.   System.out.println("After Reverse ="+strone);
  11.  
  12. if(String.valueOf(strone).compareTo(String.valueOf(strtwo))==0)
  13. return true;
  14.     else
  15.     return false;
  16. }
  17. public static void main(String[] args) {
  18. boolean ispalindrome= isPalindrome("DeleveleD");
  19. System.out.println(ispalindrome);
  20.  
  21.     }

  22. }

Output

  1. Orginal String =deleveled
  2. After Reverse =deleveled
  3. true

check palindrome or not ignore case sensitive

How to Delete folder and subfolders using Java 8

  • How to delete folder with all files and sub folders in it using java 8.
  • We can use java 8 Stream to delete folder recursively 
  • Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  • .sorted(Comparator.reverseOrder())
  • .map(Path::toFile)
  • .peek(System.out::println)
  • .forEach(File::delete);

  1. Files.walk -  this method return all files/directories below the parent folder
  2. .sorted - sort the list in reverse order, so the folder itself comes after the including subfolders and files
  3. .map - map the file path to file
  4. .peek - points to processed entry
  5. .forEach - on every File object calls the .delete() method 




#1: Java Example program to delete folders and subfolders using java 8 stream

  1. package com.instanceofjava;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.FileVisitOption;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. import java.util.Comparator;
  9. /**
  10.  * @author www.Instanceofjava.com
  11.  * @category interview questions
  12.  * 
  13.  * Description: delete folders and sub folders using java 8
  14.  *
  15.  */

  16. public class DeleteFolder {

  17. public static void main(String[] args) {
  18. Path rootPath = Paths.get("C:\\Users\\Saidesh kilaru\\Desktop\\folder1");
  19. try {
  20. Files.walk(rootPath, FileVisitOption.FOLLOW_LINKS)
  21.     .sorted(Comparator.reverseOrder())
  22.     .map(Path::toFile)
  23.     .peek(System.out::println)
  24.     .forEach(File::delete);
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }

  29. }

Output:

  1. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder\file2 in sub folder.docx
  2. C:\Users\Saidesh kilaru\Desktop\folder1\subfolder
  3. C:\Users\Saidesh kilaru\Desktop\folder1\file1.docx
  4. C:\Users\Saidesh kilaru\Desktop\folder1



How to Convert integer set to int array using Java 8

  • How to convert Integer Set to primitive int array.
  • By Using java 8 Streams we can convert Set to array.
  • set.stream().mapToInt(Number::intValue).toArray();
  • Lets see an example java program on how to convert integer set to int array using java 8

#1: Java Example program on converting Integer Set to int Array

  1. package com.instanceofjava;

  2. import java.util.Arrays;
  3. import java.util.HashSet;
  4. import java.util.Set;

  5. public class SetToArray {
  6. /**
  7.  * @author www.Instanceofjava.com
  8.  * @category interview programming questions
  9.  * 
  10.  * Description: convert Integer set to int array using java 8
  11.  *
  12.  */
  13. public static void main(String[] args) {
  14. Set<Integer> hashset= new HashSet<>(Arrays.asList(12,34,56,78,99));
  15. int[] array = hashset.stream().mapToInt(Number::intValue).toArray();
  16. for (int i : array) {
  17. System.out.println(i);
  18. }

  19. }

  20. }

Output:

  1. 34
  2. 99
  3. 56
  4. 12
  5. 78





integer set to integer array java


In Java, a Set is a collection that contains no duplicate elements and is unordered. To convert a Set to an array, you can use the toArray() method of the Set interface. This method returns an array containing all of the elements in the Set in the order they are returned by the iterator.

Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
set.add(3);

Integer[] array = set.toArray(new Integer[set.size()]);



In this example, we first create a HashSet of integers, add some elements to it, then we use the toArray method to convert it to an array of integers.

toArray(T[] a) method where we can pass an empty array of a specific type, the method will fill the array with the elements from the set, this is useful if you know the size of the array that you need.

converting a Set to an array in Java can be done using the toArray() method of the Set interface. The method returns an array containing all of the elements in the Set in the order they are returned by the iterator. This method can also accept an empty array of a specific type, the method will fill the array with the elements from the set.

Select Menu