All posts by Ravi Kumar

Custom Exception Handling in Python

Hello folks, In the previous post we have got the basic understanding of Exception handling in python. And, Today’s agenda will be custom exception handling – how we can force raise an exception, define and create custom Exception classes.

Let us imagine you need to write a code to validate your input and the validation criteria is input should be an integer and it should be between 1 to 10. If the validation criteria fail, we have to throw valid exceptions.

My first solution will be something like this.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            print("input is invalid")
    except Exception as ex:
        print(ex)

But in this code we have ignored various scenarios like

  • Input maybe not integers and then mathematical operators will not work and it will throw an exception.
  • we are not actually raising an exception if the validation criteria do not match.

Raise Custom Exception

so let us say how can we force raise any exception. To do it, we use the raise keyword in python. so modify the above code and use the raise keyword in the else block.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):
            print('input is valid')
        else:
            raise Exception("Input is Invalid")
    except Exception as ex:
        print(ex)

Create Custom Exception Class

Now what we want to do is to handle the validation criteria and throw custom exceptions based on validation criteria. so create custom Exception classes.

class VALRANGEERROR(Exception):
    def __init__(self,message):
        self.message=message
        super().__init__(self.message)

Here we have created a class called VALRANGEERROR and setting its message in constructor so that we can provide custom messages while raising this exception. After this modify our method to raise our custom Exception class.

def isvalid_input(val):
    try:
        if(val > 0 and val <= 10):   
            print('input is valid')
        else:
            raise VALRANGEERROR("Input is not in range")
    except ValueError as ex:
        print(f"Value Error - {ex}")
    except VALRANGEERROR as ex:
        print(f"Custom Exception - {ex}")
    except Exception as ex:
        print(ex)

So, to summarise this, use the raise keyword to force raise an exception. To implement a custom Exception class, Create a class that inherits from class Exception and assigns the message field in the constructor.

Exception handling in Python

Exception or Error

There can be 2 type of error – Syntax Error or Exceptions.

Synax error encounters if you do not follow language syntax guidelines. common scenarios to face such errors are:

  1. you do not follow proper indentation.
if a= 0 print(a) else print('NA')

2. Suppose you have a method which takes 2 arguments and while calling it, you are providing only one argument.

def return_sum(a,b):
    return a+ b

val = return_sum(3)

There are multiple scenarios like this. In short, a syntax error occurs if the python interpreter fails to parse your code. Now let us discuss exception.

Exceptions are any unwanted thing which may interrupt the control flow of program.

Common Exceptions which you may face with python are – Name Error, Type Error, Runtime Error, or when you are working with files. In short, we can call exception as error faced while coding execution.

a = 10
b = a/0
 #Division by 0 Error
print("Var"+ 1) #Type Error 
print(c) #Name Error
with open('filedoesnotexist') as f: #OSError
    f.read()

your code will break as the exception encounters. Here you can see that control flow of the program is stopped because of ZeroDivisionError and that’s why the code below that statement never gets executed.

Exception Handling

To solve these scenarios we need to perform exception handling. If I am asked to give a crisp description of these keywords, I will say something like this.

put your IO method or DB related methods in a try block in which you think exception may occur. If an exception occurs, Handle it in Except block. If there is no exception, Put it in the else block. And if you want to run some methods whether exceptions are encountered or not, put it in finally block like cleaning up activity, closing the DB connections or releasing the resources.

There are 4 Keyword for Exception handling in python.

  • Try: Run this code
  • Except – Run this code if Exception occurs
  • Else – Run this code if Exception does not occur
  • Finally – Run this code always whether an Exception occurs or not.

Let us consider you want to write a program to get the value of a variable from a file and then delete it. If the file does not exist then you reset the value to 0 in the file.

import os
val=None
try:
    with open('filedoesnotexist.txt') as f:
        val = f.read()
except Exception as identifier:
    val=0
    with open('filedoesnotexist.txt','w') as f:
        f.write(str(val))
else:
    os.remove('filedoesnotexist.txt')
    print("Exception did not occured. Good Job")
finally:
    print(val)
    

To avoid the Name Error i have created val variable globally as it is being used in try, except and finally block. There is Input output operation so i have put the logic to read filedoesnotexist.txt in try block. If the file does not exist, we are resting the value of val to 0 and writing it to filedoesnotexist.txt. And if the file exists then we will not get any error so i am deleting that file and finally printing the value of val variable.

I Hope you got the basic idea of Exception handling. In the next post, I will tell you how to raise custom exception, create user defined Exception and how to debug the stack trace.

Hackerrank java Introduction loops II

In this post, we will solve Hackerrank Java Introduction loops II Challenge.

Problem statement :

You are given queries in the form of a, b, and n. For each query, print the series corresponding to the given a, b, and n values as a single line of space-separated integers.

Explanation

Here we have been given 3 things – a, b, n. so now try to learn the series pattern.

you are given q queries means you have to loop through or process the series q times. if you will concentrate on the series structure you will get the series pattern.
 

we are having a geometric progression of 2 multiplied by b and we are adding this with a.

Example:

first term = a + pow(2,0)*b = 5 + 1*3 = 8
second term = a + pow(2,0)*b + pow (2,1)*b = 5 + 1*3 + 2*3 = 14
third term =  a + pow(2,0)*b + pow (2,1)*b + pow (2,2)*b = 5 + 1*3 + 2*3 + 4*3 = 26
similarly
nth term =  a + pow(2,0)*b + pow (2,1)*b + pow (2,2)*b + ——- + pow (2,n-1)*b
 
so what we will do is that.. we will make a loop and iterate it to n-1 times starting from 0.
 
 for (int j = 0; j < n; j++) {
   a += (int) Math.pow(2, j) * b ;
    System.out.print(a + " ");
}

for more clarification watch – 

If you have any confusion please let me know in the comment box. I would be happy to help you. you can subscribe to the channel if you want to learn more about hackerrank java challenges. 

Strings – Introduction

Introduction: –

Strings are called character array. i.e. sequence of characters.
This is a class that is defined in java.lang package.

 Always Remember it is not a data type.

This is one of the most important topics from which questions are asked in interviews.

Declaration of Strings: –

String string_name = “put your content inside double quotes”;
Example:
String s = “Ravi”;
If you will use char then use a single quote and for string use double-quotes.
String class has many inbuilt methods. Let’s explore them –

How to find the length of String?

The string class has a length() method for this.
String s = “Ravi”;
s.length(); // it will return the length of string.

How to change cases of String?

They have inbuilt methods like touppercase, tolowercase .. etc.
 in the next post, I will tell you how to convert from int to string and vice versa.

Java – Introduction

In this post, we will learn the introduction of java. 

Introduction:-

What is Java

A general-purpose computer programming language designed to produce programs that will run on any computer system.

Slogan of JAVA

“Write once, run anywhere” (WORA),



Features of java: –

Why Java

  1. Easy to learn
  2. It is an object-oriented programming language.
  3. It has a Rich API.
  4. powerful development tools
  5. great collection of open source libraries.
  6. wonderful community support.
  7. Free
  8. Excellent documentation
  9. Platform independent.
  10. Scalable
  11. Great Carrier opportunities.

Naming Convention

In java, mainly the following entities are there. There is some standard for naming every entity. It is not forced but it is suggested to follow. 

  • Package

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.  

Subsequent components of the package name vary according to an organization’s own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.

  • class

Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive.

Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).

  • Interface

Interface names should be capitalized like class names.

  • Methods

Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.  

  • Variable

Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. 

Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.

  Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use.   

One-character variable names should be avoided except for temporary “throwaway” variables. 

Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters

  • Constant

The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores (“_”).

ANSI constants should be avoided, for ease of debugging.

SUMMARY

Naming Convention

  1. Constant should be in Uppercase.
  2. The variable name should start with lowercase.
  3. Method name starts with lowercase and it should be a verb.
  4. package name starts with lowercase.
  5. The interface name should start with an uppercase letter.
  6. The class name should start with an uppercase letter.

And if you have a long name consisting of more than 2 words then always starts the second word with uppercase letter.   Example:   if we want to make a variable whose name is myarray- (it consists of my and array). so make the “A” of array in upper case.

Source:
http://www.oracle.com/technetwork/java/codeconventions-135099.html