Ryan Davies
Ryan Davies

Reputation: 616

Try Except Not Working With Email Function

Hello all I've got a piece of code that I'm using to send an email encase there is some kind of error when connecting to an Oracle database. The Send_Email function works perfectly fine outside of the Try Except statement but doesn't seem to work within the Try Except statement?

The reason behind this code was because the Oracle database went down today and my SQL query couldn't run. I just wanted to create a simple Try Except statement that works with my Send_Email function and i can send myself and email with the error within the body of the email. The error that originally came up was ORA-12514 cx_Oracle.DatabaseError. But regardless of the error I just want to be aware of what the exception is automatically via email.

import cx_Oracle
import pandas as pd

def Send_Email(to, cc='', bcc='', subject='', body='', attachment='' ):
    import win32com.client
    outlook = win32com.client.Dispatch('outlook.application')
    mail = outlook.CreateItem(0)
    mail.To = to
    mail.CC = cc
    mail.BCC = bcc
    mail.Subject = subject
    mail.body = body
    if attachment == '':
        pass
    else:
        mail.Attachments.Add(Source=attachment)
    mail.send


connection = cx_Oracle.connect('username', 'password', 'hostname:port/SERVICENAME')

try:
    df = pd.read_sql_query("SELECT * FROM TABLE", connection)
except cx_Oracle.DatabaseError as e:
    Send_Email(to='[email protected]', subject='AUTO: Database Error', body=str(e))
except Exception as e:
    Send_Email(to='[email protected]', subject='AUTO: Other Error', body=str(e))
finally:
    print('Working')

Upvotes: 0

Views: 142

Answers (1)

Ctznkane525
Ctznkane525

Reputation: 7465

Put your database connection in the try like this. When it cannot connect, it happens before the try section.

I want to note, a good way to retest this on your local machine would be to change your tnsnames (or whatever file you are using for configuration) to a setting that doesn't exist. That way you can test an outage without changing the code.

try:
connection = cx_Oracle.connect('username', 'password', 'hostname:port/SERVICENAME')
    df = pd.read_sql_query("SELECT * FROM TABLE", connection)
except cx_Oracle.DatabaseError as e:
    Send_Email(to='[email protected]', subject='AUTO: Database Error', body=str(e))
except Exception as e:
    Send_Email(to='[email protected]', subject='AUTO: Other Error', body=str(e))
finally:
    print('Working')

Upvotes: 2

Related Questions